In our previous article, we covered how to create easy pages in Flask and use Jinja2 since the templating engine. Now, let’s uncover how Flask handles requests.
Understanding how HTTP requests art work and how to order them in Flask is very important, as this lets you assemble further interactive and dynamic web apps, akin to development a sort, API endpoints, and coping with report uploads.
Without further ado, let’s get started.
So, What’s an HTTP Request?
An HTTP request is a message sent, maximum regularly by the use of a browser, to the server inquiring for wisdom or to perform an movement. For example, while you visit a webpage, your browser sends a GET request to the server to retrieve the internet web page’s content material subject matter.
There are a variety of different types of HTTP requests, and Flask can maintain all of them, at the side of GET
to retrieve wisdom, POST
to send wisdom to the server like submitting a sort, PUT
to switch present wisdom on the server, and DELETE
to delete wisdom from the server.
Coping with Requests in Flask
Flask makes coping with requests easy by the use of the use of routes. In our previous articles, we used routes to create static and dynamic pages. By way of default, routes most simple respond to GET
requests, then again you’ll merely maintain other HTTP methods by the use of specifying them throughout the route.
Assuming we have a slightly internet web page at /contact
, we maximum without a doubt would want the internet web page to maintain each and every GET
and POST
requests to allow consumers to load the internet web page, along with to publish the form. To make the internet web page maintain the ones two HTTP methods, we will cross throughout the methods
argument, for example:
@app.route('/contact', methods=['GET', 'POST']) def publish(): if request.approach == 'POST': wisdom = request.form['input_data'] return render_template('contact.html', wisdom=wisdom) return render_template('contact.html')
In this example, consumers can load the /contact
internet web page. When the form is submitted, Flask retrieves the form wisdom and passes it to the contact.html
template. Then, all the way through the template, you’ll get entry to and process the data the use of Jinja2 templating.
Working with Query Parameters
Data may be passed to a URL by the use of query parameters. This is often came upon on a search internet web page where the quest query is passed as a query parameter. The ones are the parts of the URL after a ?
, like /search?query=flask
. Flask makes it easy to get entry to query parameters with the request.args
dictionary, for example:
@app.route('/search') def search(): query = request.args.get('query') # Meilisearch # See: https://github.com/meilisearch/meilisearch-python end result = index.search(query) if query: return render_template('search.html', end result=end result) return 'No search query equipped.'
In this case, when an individual visits /search?query=flask
, we take the query and use it to retrieve the quest end result, which is then passed to the search.html
template for rendering.
Coping with JSON Data
When development an API, we’d like the data delivered in JSON structure. Flask provides a simple strategy to maintain JSON wisdom in requests with the jsonify
function. Proper right here’s an example of coping with JSON wisdom:
from flask import jsonify @app.route('/api/wisdom') def api_data(): return make_response(jsonify({"message": 'Just right fortune'}), 200)
Coping with Record Uploads
Flask moreover makes coping with report uploads easy, the use of the request.knowledge
object.
@app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.approach == 'POST': report = request.knowledge['file'] report.save(f'/uploads/{report.filename}') return redirect(url_for('index.html'))
In this example, when an individual submits a report by the use of the form, Flask saves the report to the required record and then redirects the individual to the homepage.
Request Headers and Cookies
Each and every so regularly you moreover need to get headers or cookies from the request to your app, akin to for passing authentication or tracking particular person wisdom. Flask provides easy get entry to to headers through request.headers
and cookies through request.cookies
. Proper right here’s a elementary example of the way we use it to authenticate for an API endpoint:
@app.route('/api/wisdom') def check out(): auth = request.headers.get('Authorization') nonce = request.cookies.get('nonce') # Simple authentication check out if auth == 'Bearer X' and nonce == 'Y': return jsonify({"message": "Authenticated"}), 200 else: return jsonify({"message": "Unauthorized"}), 401
Wrapping up
Flask makes coping with HTTP requests a breeze. Whether or not or now not you’re working with elementary GET
requests, coping with form submissions with POST
, or dealing with further complex scenarios like JSON wisdom and report uploads, it provides the APIs, functions, and power you want to get the method achieved. We’ve most simple scratched the outdoor of Flask’s request-handling options, then again expectantly, this gives you a solid foundation to begin out development your own Flask apps.
The publish How one can Care for HTTP Requests in Flask seemed first on Hongkiat.
Supply: https://www.hongkiat.com/blog/handle-http-requests-flask/
0 Comments