{"id":2672,"date":"2024-10-25T13:00:55","date_gmt":"2024-10-25T13:00:55","guid":{"rendered":"http:\/\/suimy.me\/?p=2672"},"modified":"2024-10-30T17:15:26","modified_gmt":"2024-10-30T17:15:26","slug":"how-to-handle-http-requests-in-flask","status":"publish","type":"post","link":"http:\/\/suimy.me\/index.php\/2024\/10\/25\/how-to-handle-http-requests-in-flask\/","title":{"rendered":"How to Handle HTTP Requests in Flask"},"content":{"rendered":"

In our previous article, we covered how to create simple pages in Flask<\/a> and use Jinja2 as the templating engine. Now, let\u2019s explore how Flask handles requests.<\/p>\n

Understanding how HTTP requests work and how to manage them in Flask is key, as this allows you to build more interactive and dynamic web apps, such as building a form, API endpoints, and handling file uploads.<\/p>\n

\"Flask\"Flask<\/span><\/span> <\/figure>\n

Without further ado, let\u2019s get started.<\/p>\n

So, What\u2019s an HTTP Request?<\/h4>\n

An HTTP request is a message sent, usually by a browser, to the server asking for data or to perform an action. For example, when you visit a webpage, your browser sends a GET request to the server to retrieve the page\u2019s content.<\/p>\n

There are several different types of HTTP requests, and Flask can handle all of them, including GET<\/code> to retrieve data, POST<\/code> to send data to the server like submitting a form, PUT<\/code> to update existing data on the server, and DELETE<\/code> to delete data from the server.<\/p>\n

Handling Requests in Flask<\/h4>\n

Flask<\/strong> makes handling requests straightforward by using routes<\/strong>. In our previous articles, we used routes to create static and dynamic pages. By default, routes only respond to GET<\/code> requests, but you can easily handle other HTTP methods by specifying them in the route.<\/p>\n

Assuming we have a contact page at \/contact<\/code>, we probably would want the page to handle both GET<\/code> and POST<\/code> requests to allow users to load the page, as well as to submit the form. To make the page handle these two HTTP methods, we can pass in the methods<\/code> argument, for example:<\/p>\n

\r\n@app.route('\/contact', methods=['GET', 'POST'])\r\ndef submit():\r\n    if request.method == 'POST':\r\n        data = request.form['input_data']\r\n        return render_template('contact.html', data=data)\r\n    return render_template('contact.html')\r\n<\/pre>\n

In this example, users can load the \/contact<\/code> page. When the form is submitted, Flask retrieves the form data and passes it to the contact.html<\/code> template. Then, within the template, you can access and process the data using Jinja2 templating.<\/p>\n

Working with Query Parameters<\/h4>\n

Data may be passed to a URL via query parameters. This is commonly found on a search page where the search query is passed as a query parameter. These are the parts of the URL after a ?<\/code>, like \/search?query=flask<\/code>. Flask makes it easy to access query parameters with the request.args<\/code> dictionary, for example:<\/p>\n

\r\n@app.route('\/search')\r\ndef search():\r\n    query = request.args.get('query')\r\n    \r\n    # Meilisearch\r\n    # See: https:\/\/github.com\/meilisearch\/meilisearch-python\r\n    result = index.search(query)\r\n\r\n    if query:\r\n        return render_template('search.html', result=result)\r\n    return 'No search query provided.'\r\n<\/pre>\n

In this case, when a user visits \/search?query=flask<\/code>, we take the query and use it to retrieve the search result, which is then passed to the search.html<\/code> template for rendering.<\/p>\n

Handling JSON Data<\/h4>\n

When building an API, we need the data delivered in JSON format. Flask provides a simple way to handle JSON data in requests with the jsonify<\/code> function. Here\u2019s an example of handling JSON data:<\/p>\n

\r\nfrom flask import jsonify\r\n\r\n@app.route('\/api\/data')\r\ndef api_data():\r\n    return make_response(jsonify({\"message\": 'Success'}), 200)\r\n<\/pre>\n

Handling File Uploads<\/h4>\n

Flask also makes handling file uploads easy, using the request.files<\/code> object.<\/p>\n

\r\n@app.route('\/upload', methods=['GET', 'POST'])\r\ndef upload_file():\r\n    if request.method == 'POST':\r\n        file = request.files['file']\r\n        file.save(f'\/uploads\/{file.filename}')\r\n        return redirect(url_for('index.html'))\r\n<\/pre>\n

In this example, when a user submits a file via the form, Flask saves the file to the specified directory and then redirects the user to the homepage.<\/p>\n

Request Headers and Cookies<\/h4>\n

Sometimes you also need to get headers or cookies from the request in your app, such as for passing authentication or tracking user data. Flask provides easy access to headers through request.headers<\/code> and cookies through request.cookies<\/code>. Here\u2019s a basic example of how we use it to authenticate for an API endpoint:<\/p>\n

\r\n@app.route('\/api\/data')\r\ndef check():\r\n    auth = request.headers.get('Authorization')\r\n    nonce = request.cookies.get('nonce')\r\n\r\n    # Simple authentication check\r\n    if auth == 'Bearer X' and nonce == 'Y':\r\n        return jsonify({\"message\": \"Authenticated\"}), 200\r\n    else:\r\n        return jsonify({\"message\": \"Unauthorized\"}), 401\r\n<\/pre>\n

Wrapping up<\/h4>\n

Flask makes handling HTTP requests a breeze. Whether you\u2019re working with basic GET<\/code> requests, handling form submissions with POST<\/code>, or dealing with more complex scenarios like JSON data and file uploads, it provides the APIs, functions, and tools you need to get the job done. We\u2019ve only scratched the surface of Flask\u2019s request-handling capabilities, but hopefully, this gives you a solid foundation to start building your own Flask apps.<\/p>\n

The post How to Handle HTTP Requests in Flask<\/a> appeared first on Hongkiat<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"

In our previous article, we covered how to create simple pages in Flask and use Jinja2 as the templating engine. […]<\/p>\n","protected":false},"author":1,"featured_media":2674,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[15],"tags":[],"_links":{"self":[{"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/posts\/2672"}],"collection":[{"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/comments?post=2672"}],"version-history":[{"count":2,"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/posts\/2672\/revisions"}],"predecessor-version":[{"id":2675,"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/posts\/2672\/revisions\/2675"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/media\/2674"}],"wp:attachment":[{"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/media?parent=2672"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/categories?post=2672"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/tags?post=2672"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}