Processing requests
demand
How can the data be correctly fetched when the data requested by the client needs to be read in view writing?
The data carried by the request may appear in different locations in the HTTP message, and different methods need to be used to obtain parameters.
1. URL path parameters (dynamic routing)
For example, there is an interface address requesting access to / users/123, where 123 is actually a specific request parameter, indicating the information of user 123. How to extract 123 data from the url?
Unlike Django's direct way of writing regular expressions when defining routes, Flask adopts converter syntax:
@app.route('/users/<user_id>') def user_info(user_id): print(type(user_id)) return 'hello user {}'.format(user_id)
Example code:
from flask import Flask app = Flask(__name__) @app.route('/users/<user_id>') def user_info(user_id): print(type(user_id)) return 'hello user {}'.format(user_id) if __name__ == '__main__': app.run()
Operation effect:
The < > here is a converter, which defaults to string type, that is, the data at this location is matched in string format, and the string is used as the data type and user_id is the parameter name passed into the view.
Flask also provides other types of converters
DEFAULT_CONVERTERS = { 'default': UnicodeConverter, 'string': UnicodeConverter, 'any': AnyConverter, 'path': PathConverter, 'int': IntegerConverter, 'float': FloatConverter, 'uuid': UUIDConverter, }
Using the above example to match data with integer, you can use it as follows:
@app.route('/users/<int:user_id>') def user_info(user_id): print(type(user_id)) return 'hello user {}'.format(user_id) @app.route('/users/<int(min=1):user_id>') def user_info(user_id): print(type(user_id)) return 'hello user {}'.format(user_id)
Example code 1:
from flask import Flask app = Flask(__name__) @app.route('/users/<int:user_id>') def user_info(user_id): print(type(user_id)) return 'hello user {}'.format(user_id) if __name__ == '__main__': app.run()
Operation effect:
Example code 2:
from flask import Flask app = Flask(__name__) @app.route('/users/<int(min=3):user_id>') def user_info(user_id): print(type(user_id)) return 'hello user {}'.format(user_id) if __name__ == '__main__': app.run()
Operation effect:
Custom converter
If a match is needed, extract / SMS_ For the mobile phone number data in codes / 18512345678, the built-in converter in Flask cannot meet the requirements. At this time, you need to customize the converter.
Definition method
There are three steps to customize the converter
-
Create a converter class and save the regular expression when matching
from werkzeug.routing import BaseConverter class MobileConverter(BaseConverter): """ Mobile number format """ regex = r'1[3-9]\d{9}'
- Note that the regex name is fixed
-
Inform the flash application of the custom converter
app = Flask(__name__) # Add a custom converter to the converter dictionary and specify the name of the converter when it is used: mobile app.url_map.converters['mobile'] = MobileConverter
-
Define where the converter is used
@app.route('/sms_codes/<mobile:mob_num>') def send_sms_code(mob_num): return 'send sms code to {}'.format(mob_num)
Example code:
from flask import Flask from werkzeug.routing import BaseConverter class MobileConverter(BaseConverter): """Mobile number format""" regex = r'1[3-9]\d{9}' app = Flask(__name__) # Add a custom converter to the converter dictionary and specify the name of the converter when it is used: mobile app.url_map.converters['mobile'] = MobileConverter @app.route('/sms_codes/<mobile:mob_num>') def send_code(mob_num): return 'send sms code to {}'.format(mob_num) if __name__ == '__main__': app.run()
Operation effect:
2. Other parameters
If you want to get the parameters passed elsewhere, you can read them through the request object provided by Flask.
Parameters in different locations are stored in different attributes of request
attribute | explain | type |
---|---|---|
data | Record the requested data and convert it to a string | * |
form | Record the form data in the request | MultiDict |
args | Record the query parameters in the request | MultiDict |
cookies | Record cookie information in the request | Dict |
headers | Record the message header in the request | EnvironHeaders |
method | Record the HTTP method used by the request | GET/POST |
url | Record the URL address of the request | string |
files | Record the file requested to be uploaded | * |
For example, would you like to get the request / articles? channel_ Channel in id = 1_ The parameter ID can be used as follows:
from flask import request @app.route('/articles') def get_articles(): channel_id = request.args.get('channel_id') return 'you wanna get articles of channel {}'.format(channel_id)
Example code:
from flask import Flask, request app = Flask(__name__) @app.route('/articles') def get_articles(): channel_id = request.args.get('channel_id') return 'you wanna get articles of channel {}'.format(channel_id) if __name__ == '__main__': app.run()
Operation effect:
Upload pictures
The client uploads the picture to the server and saves it to the server
from flask import request @app.route('/upload', methods=['POST']) def upload_file(): f = request.files['pic'] # with open('./demo.png', 'wb') as new_file: # new_file.write(f.read()) f.save('./demo.png') return 'ok'
Example code:
from flask import Flask, request app = Flask(__name__) @app.route('/upload', methods=['POST']) def upload_file(): f = request.files['pic'] # with open('./demo.png', 'wb') as new_file: # new_file.write(f.read()) f.save('./demo.png') return 'ok' if __name__ == '__main__': app.run()
[the effect of with open is the same as that of f.save, and f.save is a encapsulated method]
Post man upload picture test: