YouTip LogoYouTip

Flask Views Functions

View functions are the core part of a Flask application, responsible for handling requests and generating responses. View functions are closely integrated with routes, mapping URLs to specific view functions through routing. The following is a detailed explanation of Flask view functions, including how to define them, use request data, return responses, and handle errors, etc. 1. **Defining View Functions**: View functions are the core functionality for processing requests and returning responses. 2. **Receiving Request Data**: Use the `request` object to get URL parameters, form data, query parameters, etc. 3. **Returning Responses**: Can return strings, HTML, JSON, or custom response objects. 4. **Processing Requests and Responses**: Use the `request` object and `make_response` to process requests and generate custom responses. 5. **Handling Errors**: Handle exceptions within view functions or use Flask's error handling mechanism. 6. **View Function Decorators**: Use decorators like `@app.before_request`, `@app.after_request` to handle logic before and after requests. 7. **Status Codes Returned by View Functions**: Can specify HTTP status codes to indicate the result of request processing. ### 1. Defining View Functions A view function is an ordinary Python function that receives requests and returns responses. View functions are typically used with routes, mapping URLs to view functions through decorators. ## Example from flask import Flask app = Flask( __name__ ) @app.route('/') def home(): return'Hello, World!' * `@app.route('/')`: Maps the root URL `/` to the `home` view function. * `def home()`: The view function, returning the string `'Hello, World!'` as the response. ### 2. Receiving Request Data View functions can receive different types of request data, including URL parameters, form data, query parameters, etc. Getting URL parameters: ## Example @app.route('/greet/') def greet(name): return f'Hello, {name}!' * `` is a URL parameter passed to the view function `greet`. Getting form data: ## Example from flask import request @app.route('/submit', methods=['POST']) def submit(): username = request.form.get('username') return f'Form submitted by {username}!' request.form.get('username'): Gets the username field from form data in POST requests. Getting query parameters: ## Example @app.route('/search') def search(): query = request.args.get('query') return f'Search results for: {query}' request.args.get('query'): Gets the query parameter from GET requests. ### 3. Returning Responses View functions can return various types of responses, including strings, HTML, JSON, or custom response objects. Returning strings: ## Example @app.route('/message') def message(): return'This is a simple message.' Returning HTML templates: ## Example from flask import render_template @app.route('/hello/') def hello(name): return render_template('hello.html', name=name) render_template('hello.html', name=name): Renders the HTML template hello.html and passes the name variable to the template. Returning JSON data: ## Example from flask import jsonify @app.route('/api/data') def api_data(): data ={'key': 'value'} return jsonify(data) jsonify(data): Converts a Python dictionary to a JSON response. Returning custom response objects: ## Example from flask import Response @app.route('/custom') def custom_response(): response = Response('Custom response with headers', status=200) response.headers['X-Custom-Header']='Value' return response Response('Custom response with headers', status=200): Creates a custom response object and sets response headers. ### 4. Processing Requests and Responses View functions can access request objects and generate responses based on request data. You can use the request object to get request information and make_response to create custom responses. Using the request object: ## Example from flask import request @app.route('/info') def info(): user_agent = request.headers.get('User-Agent') return f'Your user agent is {user_agent}' request.headers.get('User-Agent'): Gets the User-Agent information from request headers. Using make_response: ## Example from flask import make_response @app.route('/header') def custom_header(): response = make_response('Response with custom header') response.headers['X-Custom-Header']='Value' return response make_response('Response with custom header'): Creates a response object and sets custom header information. ### 5. Handling Errors You can handle exceptions or errors within view functions, or use Flask's error handling mechanism to handle errors in the application. Handling errors in view functions: ## Example @app.route('/divide//') def divide(x, y): try: result = x / y return f'Result: {result}' except ZeroDivisionError: return'Error: Division by zero',400 Uses try-except statement to handle division by zero error, returning a custom error message and status code. Global error handling: ## Example @app.errorhandler(404) def not_found(error): return'Page not found',404 @app.errorhandler(404): Defines a function to handle 404 errors. ### 6. View Function Decorators In addition to @app.route, Flask also supports other decorators for implementing more complex functionality. Examples: * **`@app.before_request`**: Function that runs before each request is processed. * **`@app.after_request`**: Function that runs after each request is processed. * **`@app.teardown_request`**: Function that runs after the request ends, used for cleanup work. Example decorator usage: ## Example @app.before_request def before_request(): print('Before request') @app.after_request def after_request(response): print('After request') return response @app.teardown_request def teardown_request(exception): print('Teardown request') ### 7. Status Codes Returned by View Functions View functions can not only return content but also specify HTTP status codes. ## Example @app.route('/status') def status(): return'Everything is OK',200 Returns status code 200 indicating the request was successful. Returning response objects with status codes: ## Example from flask import Response @app.route('/error') def error(): return Response('An error occurred', status=500) Returns status code 500 indicating an internal server error.
← Flask FormFlask Layout β†’