What You Need to Master
Understand the definition, roles, and applications of backend development.
Master the Flask framework.
What You Need to Prepare
Enter the following command in cmd (Windows) or terminal (Mac):
pip install flask #or pip3 install flask #or pip3.8 install flask
What You Need to Learn
Backend Development
1. Definition
Take the Jodoo webpage as an example
Frontend: The frontend of a webpage refers to the part that users interact with, including texts, images, icons, interactive effects achieved from clicking, pop-ups, and so on.
Backend: The backend refers to server operation and maintenance, database management, as well as the private APIs that connect the frontend and backend.
Private APIs: Examples include the APIs used for frontend-backend collaborative development in platforms like Jodoo, which are only used internally within the product.
Public APIs: These are services that are packaged and made available for developers to use, such as Jodoo's data API and contact API.
2. Relevant functions in Jodoo
APIs (public interfaces) are available at this development documentation address: https://hc.jodoo.com/open/10992. With the backend and API, developers can trigger Jodoo's services by sending requests from the backend along with data.
Webhook is available at this development documentation address: https://hc.jodoo.com/open/11500. A webhook is a way for Jodoo to send data to a specified endpoint or URL when a certain event occurs within the platform.
Front-end events are available at this development documentation address: https://hc.jodoo.com/doc/11825. With frontend and API, users can trigger events on a form-filling interface to call an API that has been configured by the admin to retrieve data or trigger other events.
3. Scenarios
Through the previous three sections, you might have been able to retrieve interfaces. To be specific, you have known:
How to use POSTMAN to retrieve interfaces
How to use Python to process data
How to use Python to encapsulate the interface that serves to retrieve functions
Through backend development, we can develop our own interfaces, develop services, and use data more freely.
How to develop interfaces locally
How to deploy interfaces to cloud servers (ECS)
How to backup data to databases and retrieve data from databases
Achieve the following scenarios:
Data push in Jodoo – Data processing (ECS) – Retrieve API in Jodoo (Similar to the advanced automations)
Data push in Jodoo – Data processing (ECS) – OCR (Third-party interface) – Data processing (ECS) – Retrieve API in Jodoo
Data push in Jodoo – Data processing (ECS) Jodoo –Mysql (Database):
ASP timing framework (ECS) – Retrieve API in Jodoo – Data processing (ECS) – Mysql (Database):
Front-end event in Jodoo – Data processing (ECS) – Analyze data (OCR)
Front-end event in Jodoo – Data processing (ECS) – Data validation (Validate the consistency of name and ID)
Front-end event in Jodoo – Data processing (ECS) – Access Data
Front-end event in Jodoo – Data processing (ECS) – Obtain data from Mysql – Obtain data from Others
Application examples for front-end events
Value-added Tax Invoice OCR Recognition_Demo
ID Card OCR Recognition_Demo
Database Query_Demo
Latest Logistics Information Query_Demo
ID Verification _Demo
Flask Framework
Official Document: Click to read.
Flask is a web micro-framework implemented in Python that allows us to quickly implement a website or web service using the Python language.
1. A minimal Flask app
Note: Running Flask files directly in IDLE may result in an "io.UnsupportedOperation: fileno" error. Double-clicking the .py file to run it can solve this problem!
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): # Do not duplicate the function names when receiving. return 'Hello, World!' if __name__ == '__main__': app.run(host='0.0.0.0',port=3100)
Let's take a look at it one by one:
First, we imported the Flask package:
from flask import Flask
Next, we created an instance of this class. The first parameter is the name of the app module or package. If you are using a single module (like in this example), you should use __name__ because the name will change depending on whether the module is being used as an app or imported as a module (it could be __main__ or the actual imported name). This parameter is required so that Flask knows where to find things like templates and static files.
app = Flask(__name__)
Then, we used the route() decorator to tell Flask the URL that triggers the function;
@app.route('/')
The function name is used to generate the associated URL. "At the end, the function returns the information that needs to be displayed in the user's browser.
def hello_world(): return 'Hello, World!'
The default setting is that after running the server, only your own computer can use the service, and it listens only to 127.0.0.1. So you need to add --host=0.0.0.0, this line of code tells your operating system to listen on all public IPs. In this lesson, we're only writing for the local interface, so it's not necessary to add it.
if __name__ == '__main__': app.run(host='0.0.0.0',port=3100)
2. The structure of URL
"Domain name (Host, in this case, we are running locally and using the local machine IP: 127.0.0.1) + Port + Path
Port:
if __name__ == '__main__': app.run(host='0.0.0.0',port=3100)
Path:
@app.route('/route')
You can also define multiple paths under the same port (just make sure the function names for handling the requests are not duplicated):
from flask import Flask app = Flask(__name__) @app.route('/a') def hello_world1(): #Do not duplicate the function names when receiving. return 'Hello, World!' @app.route('/b/') def hello_world2(): #Do not duplicate the function names when receiving. return 'Thank you' if __name__ == '__main__': app.run(host='0.0.0.0',port=3100)
3. Receive data
Define the interface type
@app.route('/',methods=['GET']) @app.route('/',methods=['GET', 'POST']) @app.route('/',methods=['POST'])
Receive different data
Remember to import the request module first.
from flask import Flask,request import json
Receive URL params
request.args request.args.get("canshu1")
Receive Headers
request.headers request.headers.get("xxx")
Receive data in the format of multipart/form-data or application/x-www-form-urlencoded
request.form request.form.get("xxx")
Receive data in application/json format
request.data json.loads(request.data)
from flask import Flask,request import json app = Flask(__name__) @app.route('/',methods=['GET', 'POST']) def hello_world(): print(request.args) print(request.headers) print(request.form) print(request.data) print(json.loads(request.data)) return 'success',200 if __name__ == '__main__': app.run(host='0.0.0.0',port=3100)
4. Return value
JSON format response is common, and it's easy to get started writing APIs in Flask that return JSON responses.
import json import urllib.parse # Return text return 'Hello, World!' # Return the data in the format of Json a = json.dumps({"aaa":123}) return a # Return the data in the format of x-www-from-urlencoded return urllib.parse.urlencode({"aaa":123}) return urllib.parse.urlencode({"aaa":123}) # If you don't need to return data, you only need to return the status code. return 'success',200
HTTP status code
Catching exceptions can be done using the try/except statement.
The try/except statement is used to detect errors in the try block, allowing the except statement to catch the exception and handle it.
If you don't want your program to terminate when an exception occurs, you can catch it in the try block.
The following is the syntax for a simple try/except/else statement:
try: <语句> #Runs other code except <名字>: <语句> #If a 'name' exception is raised in the try block except <名字>,<数据>: <语句> #If a 'name' exception is raised, retrieve the additional data else: <语句> #If no exception occurs
In the process of developing APIs, you can use exception handling to return different status codes!
400 Parameter error
Key | Value |
name | Name |
age | Age |
import json request_data = {"name":"ziv"} def response(): try: name = request_data['name'] age = request_data['age'] except KeyError as e: return 'Parameter error',400 else: return 'success',200
401 Unauthorized: authentication failed
if request.headers['x-jdy-signature'] != get_signature(nonce, payload, 'test-secret', timestamp): return 'fail', 401
The explanation of webhook push errors in Jodoo
After receiving the push, you need to return 2xx to indicate the successful reception of the push to Jodoo After receiving the push notification, it is necessary to return a 2xx HTTP status code to indicate the successful reception of the push to Jodoo