1. Working principle
In Flask, all client requested data are accessed through the global request object. This object is part of the request context and exists only during request processing. Flask automatically creates a request object when receiving a request, parses the data according to the request type (such as GET, POST) and content type (such as form, JSON), and encapsulates data from different sources into corresponding attributes (such as args, form, json).
2. Common methods
Query parameters (URL parameters)
use(type:
ImmutableMultiDict
) Get the query parameters in the URL.
name = ('name') # Get a single parameterall_args = .to_dict() # Convert to dictionary
Form data
Forapplication/x-www-form-urlencoded
ormultipart/form-data
Type of POST request, use。
username = ('username')
JSON data
When requestedContent-Type
forapplication/json
When usingDirectly get the parsed dictionary.
data =
File upload
passGet the uploaded file (type:
FileStorage
)。
file = ('file') if file: ('uploaded_file.txt')
Raw data
useGet unprocessed raw byte data (such as non-form, non-JSON request body).
Request header and cookies
user_agent = ('User-Agent') user_token = ('token')
3. Advanced usage
Handle multi-value parameters
When the parameter has multiple values (such as multi-check boxes), usegetlist
:
selected_ids = ('ids')
-
Forced parsing JSON
even thoughContent-Type
noapplication/json
, can also be forced to parse:
data = request.get_json(force=True)
-
Streaming large files
useRead data block by block to avoid memory overflow:
@('/upload', methods=['POST']) def upload(): def generate(): chunk_size = 4096 while True: chunk = (chunk_size) if not chunk: break # Handle chunk... return 'Upload complete'
Mixed data (form + JSON)use
Merge query parameters and form data (combination is not recommended, logic needs to be handled with caution).
4. Complete example
from flask import Flask, request, jsonify app = Flask(__name__) @('/api', methods=['GET', 'POST']) def handle_request(): # Get query parameters query_param = ('q') # Process data according to different request types if == 'POST': # Process form data username = ('username') # Process JSON data json_data = request.get_json(silent=True) # Resolution failed to return None # Process file upload uploaded_file = ('file') if uploaded_file: uploaded_file.save('uploads/' + uploaded_file.filename) return jsonify({ "query_param": query_param, "username": username, "json_data": json_data, "file_uploaded": bool(uploaded_file) }) else: return jsonify({"query_param": query_param}) if __name__ == '__main__': (debug=True)
5. Things to note
-
Request method affects data acquisition
- GET request only
args
,noneform
orfiles
。 - POST needs to be based on
Content-Type
Select the correct attribute (such asform
orjson
)。
- GET request only
Process missing data
use.get('key')
Rather than['key']
avoidKeyError
, you can specify the default value:
value = ('key', 'default')
-
JSON parsing security
- use
request.get_json(silent=True)
Avoid throwing exceptions if parsing failed. - use
force=True
When paying attention, the client may send illegal data.
- use
-
File upload security
- Limit file type and size (by
MAX_CONTENT_LENGTH
Configuration). - Verify file names to avoid path traversal vulnerabilities.
- Limit file type and size (by
6. Expand knowledge
Request hook preprocessing
use@app.before_request
Unified verification or preprocessing of data before request processing:
@app.before_request def check_auth(): if not == 'login' and not validate_token(('Token')): return jsonify({"error": "Unauthorized"}), 401
-
Third-party library extensions
- Flask-RESTful: Build a REST API to automatically parse requested data.
- Flask-WTF: Integrated WTForms, handle form validation and CSRF protection.
-
Performance optimization
- For large file uploads, use streaming or block transfer.
- Enable
gzip
Compression reduces the amount of data transmission.
Test request
Use Flask to test client mock requests:
with app.test_client() as client: response = ('/api', data={'username': 'test'}, headers={'Content-Type': 'multipart/form-data'}) assert response.status_code == 200
7. Error handling and debugging skills
1. Elegantly handle data parsing errors
When parsing client data, you may encounter format errors or illegal content, and you need to reasonably catch the exception:
@('/parse-json', methods=['POST']) def parse_json(): try: data = request.get_json() if data is None: raise ValueError("Invalid JSON") # Processing data... except ValueError as e: return jsonify({"error": str(e)}), 400
Key points:
- use
silent=True
When , no exception will be thrown even if the parsing fails, but manual check is requireddata
Is itNone
。 - For file upload errors, you can check
Whether it exists and the file object is valid.
2. Practical method for debugging requested data
During development, a quick view of the original request data helps locate issues:
@('/debug', methods=['POST']) def debug_endpoint(): print("Headers:", ) print("Raw Data:", ('utf-8')) print("Form Data:", ) return "Debug information logged"
Tool recommendations:
- Postman: Simulate complex requests (such as multipart/form-data or custom headers).
- curl command: Quick test API interface:
curl -X POST http://localhost:5000/api -H "Content-Type: application/json" -d '{"key": "value"}'
8. Security reinforcement strategy
1. Prevent common attacks
CSRF Protection:use
Flask-WTF
Extended automatic generation and verification CSRF Token:
from flask_wtf.csrf import CSRFProtect csrf = CSRFProtect(app)
Add hidden fields to the form:
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
SQL Injection Protection: Always use ORMs (such as SQLAlchemy) or parameterized queries to avoid splicing SQL strings.
XSS Protection: Escape the content entered by the user (Flask templates are automatically escaped by default).
2. File upload security practice
- Limit file extensions:
allowed_extensions = {'png', 'jpg', 'jpeg'} filename = uploaded_file.filename if '.' not in filename or ('.')[-1].lower() not in allowed_extensions: return "Invalid file type", 400
-
Prevent path traversal:use
secure_filename
Process file name:
from import secure_filename safe_filename = secure_filename(uploaded_file.filename) uploaded_file.save(f'uploads/{safe_filename}')
9. Asynchronous and Performance Optimization
1. Asynchronously handle large requests
useasync/await
Processing time-consuming operations (requires Flask 2.0+ to support asynchronous views):
@('/async-upload', methods=['POST']) async def async_upload(): data = await request.get_data() # Asynchronous processing of data (such as writing to the database) return "Processing completed"
Applicable scenarios:
- Background processing after large files are uploaded (such as video transcoding).
- Non-blocking IO operation under high concurrency.
2. Performance tuning suggestions
Configure request body size limit:
['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 # Limit to 100MB
Enable compression: Compress response data via Nginx or GzipMiddleware:
from flask_compress import Compress Compress(app)
10. Integrate with other technology stacks
1. Process data in combination with the front-end framework
-
React/Vue Form Submission: Ensure the front end
Content-Type
Matching with the backend:
// Use FormData to process file uploadconst formData = new FormData(); ('file', [0]); fetch('/api/upload', { method: 'POST', body: formData });
-
AJAX Request Processing: Flask automatic parsing
application/json
, the front-end needs to clearly set headers:
fetch('/api/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: ({ key: 'value' }) });
2. Extended data format support (such as XML)
If you need to parse XML requests, you can customize the parsing logic:
from import ElementTree @('/xml', methods=['POST']) def parse_xml(): xml_data = root = (xml_data) value = ('key').text return jsonify({"value": value})
11. Practical case: Building a RESTful API
1. User registration interface
Processing mixed data (JSON + file avatar upload):
@('/register', methods=['POST']) def register(): # parse JSON data user_data = request.get_json() username = user_data.get('username') # Process avatar files avatar = ('avatar') if avatar: (f'avatars/{secure_filename()}') # Save the user to the database (pseudocode) save_user(username) return jsonify({"status": "success"})
2. Pagination query interface
Combining query parameters and data filtering:
@('/articles', methods=['GET']) def get_articles(): page = ('page', 1, type=int) per_page = ('per_page', 10, type=int) articles = (page=page, per_page=per_page) return jsonify({ "data": [article.to_dict() for article in ], "total_pages": })
12. Summary
Flask's request data acquisition mechanism takes into account flexibility and simplicity. Developers need to choose appropriate methods based on the actual scenario:
-
Basic scene: Use directly
、
、
。
- Complex scenes: Combined with streaming processing, asynchronous operation or third-party library extension functions.
- Safety first: Always verify input, limit resources, and prevent common attacks.
By rationally designing data flow and error handling mechanisms, efficient and robust web applications can be built.
This is the end of this article about the detailed explanation of the method of obtaining Flask request data. For more relevant content on obtaining Flask request data, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!