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>\nIn 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>\nWorking 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>\nIn 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>\nHandling 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>\nHandling 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>\nIn 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>\nWrapping 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>\nThe 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}]}}