{"id":87024,"date":"2023-03-23T10:49:15","date_gmt":"2023-03-23T05:19:15","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=87024"},"modified":"2023-03-23T10:49:15","modified_gmt":"2023-03-23T05:19:15","slug":"python-flask-facts","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/","title":{"rendered":"Amazing Facts About Python Flask"},"content":{"rendered":"<p>Python Flask is a microweb framework for Python that is used for building web applications. It is classified as a microframework because it does not require particular tools or libraries. It has a small and easy-to-extend core. Flask is a lightweight framework that is easy to learn and use, and it is a great choice for small to medium-sized projects.<\/p>\n<p>Flask is based on Werkzeug and Jinja2, which are both Python libraries. Werkzeug is a utility library for handling HTTP requests and Jinja2 is a template engine for Python. These libraries provide the basic functionality for handling requests and rendering templates, respectively.<\/p>\n<h3>Features of Python Flask<\/h3>\n<p>Python Flask is a micro web framework that has several features that make it a popular choice for building web applications:<\/p>\n<h4>1. Routing<\/h4>\n<p>Flask supports routing, which refers to the process of determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on). Flask uses decorators to define routes, which makes it easy to map different URL patterns to different views in your application.<\/p>\n<p><span style=\"font-weight: 400\">Here is an example of how to define routes in a Flask application:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from flask import Flask, render_template, request\n\napp = Flask(__name__)\n\n@app.route('\/')\ndef index():\n    return 'Hello, World!'\n\n@app.route('\/about')\ndef about():\n    return 'About Page'\n\n@app.route('\/greet', methods=['GET', 'POST'])\ndef greet():\n    if request.method == 'POST':\n        name = request.form['name']\n        return f'Hello, {name}!'\n    else:\n        return render_template('greet.html')\n<\/pre>\n<p><span style=\"font-weight: 400\">In the above example, we import the Flask module and create a Flask web server from the Flask module. We then define three routes using the app.route decorator. The \/ route is the home page of the application and will return &#8220;Hello, World!&#8221; when the root URL is accessed. The \/about the route will return &#8220;About Page&#8221; when the \/about URL is accessed. The \/greet route will handle both GET and POST requests, when the user accesses the \/greet URL it will render the greet.html template, and when the user submits the form it will return the greeting message.<\/span><\/p>\n<h4>2. Template rendering<\/h4>\n<p><span style=\"font-weight: 400\">In Flask, template rendering is the process of generating an HTML page from a template file and some data. Flask uses the Jinja2 template engine to render templates, which is a powerful and easy-to-use template engine for Python.<\/span><\/p>\n<p>Jinja2 allows you to use template inheritance, which means that you can use a base template and extend it with other templates to avoid repeating common elements in your views. This makes it easy to keep your views clean and maintainable.<\/p>\n<p><span style=\"font-weight: 400\">Here is an example of how to render a template in a Flask application:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from flask import Flask, render_template\n\napp = Flask(__name__)\n\n@app.route('\/')\ndef index():\n    return render_template('index.html', title='Home')\n\n@app.route('\/about')\ndef about():\n    return render_template('about.html', title='About')\n<\/pre>\n<p><span style=\"font-weight: 400\">In this example, we import the Flask module and create a Flask web server from the Flask module. We then define two routes using the app.route decorator. The \/ route is the home page of the application and will render the index.html template when the root URL is accessed. The \/about route will render the about.html template when the \/about URL is accessed.<\/span><\/p>\n<p><span style=\"font-weight: 400\">It&#8217;s worth noting that in this example we&#8217;re using the render_template function to render a template file and passing in the title variable that will be available in the template as {{title}}.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Also, templates are usually stored in a separate folder called templates, Flask looks for templates in the templates folder by default, so you should create a folder named templates in the root directory of your application and put all your templates files there.<\/span><\/p>\n<p><span style=\"font-weight: 400\">In the template files (index.html and about.html) you can use Jinja2 template language for dynamic parts of the template like loops, conditions, variables, and so on.<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n  &lt;head&gt;\n    &lt;title&gt;{{title}}&lt;\/title&gt;\n  &lt;\/head&gt;\n  &lt;body&gt;\n    &lt;h1&gt;Welcome to the {{title}} page!&lt;\/h1&gt;\n  &lt;\/body&gt;\n&lt;\/html&gt;\n\nIn this example, the {{title}} variable is used to display the title of the page in the &lt;title&gt; and &lt;h1&gt; tags.\n<\/pre>\n<h4>3. Form handling<\/h4>\n<p>In Flask, form handling is the process of receiving and validating user input from HTML forms. Flask provides built-in support for handling forms, which makes it easy to create forms and validate user input.<\/p>\n<p>Here is an example of how to handle a form in a Flask application:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from flask import Flask, render_template, request, redirect, url_for\n\napp = Flask(__name__)\n\n@app.route('\/')\ndef index():\n    return render_template('form.html')\n\n@app.route('\/submit', methods=['POST'])\ndef submit():\n    name = request.form['name']\n    email = request.form['email']\n    message = request.form['message']\n    return redirect(url_for('success', name=name, email=email, message=message))\n\n@app.route('\/success\/&lt;name&gt;\/&lt;email&gt;\/&lt;message&gt;')\ndef success(name, email, message):\n    return f'Hello, {name}! Your email is {email} and your message is {message}'\n<\/pre>\n<p>In this example, we import the Flask module and create a Flask web server from the Flask module. We then define three routes using the app.route decorator. The \/ route is the home page of the application and will render the form.html template when the root URL is accessed. The \/submit route will handle the form submission and extract the data from the form fields using the request.form dictionary. The \/success\/&lt;name&gt;\/&lt;email&gt;\/&lt;message&gt; route will display the message with the name, email, and message passed as the url parameter.<\/p>\n<p>The form.html file should contain a form with the appropriate fields and a submit button like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;form action=\"{{ url_for('submit') }}\" method=\"post\"&gt;\n    &lt;label for=\"name\"&gt;Name:&lt;\/label&gt;\n    &lt;input type=\"text\" name=\"name\" id=\"name\" required&gt;\n    &lt;br&gt;\n    &lt;label for=\"email\"&gt;Email:&lt;\/label&gt;\n    &lt;input type=\"email\" name=\"email\" id=\"email\" required&gt;\n    &lt;br&gt;\n    &lt;label for=\"message\"&gt;Message:&lt;\/label&gt;\n    &lt;textarea name=\"message\" id=\"message\" required&gt;&lt;\/textarea&gt;\n    &lt;br&gt;\n    &lt;input type=\"submit\" value=\"Submit\"&gt;\n&lt;\/form&gt;\n<\/pre>\n<p>In this example, the form is submitted to the \/submit route using the POST method, and the input fields are named as &#8216;name&#8217;, &#8217;email&#8217;, and &#8216;message&#8217; and are required.<\/p>\n<h4>4. Support for extensions<\/h4>\n<p>Flask supports the use of extensions, which are third-party libraries that add additional functionality to your application. There are many Flask extensions available, such as Flask-SQLAlchemy, which is an extension that adds support for working with databases, and Flask-WTForms, which is an extension that adds support for working with forms.<\/p>\n<p><span style=\"font-weight: 400\">Here is an example of how to use the Flask-SQLAlchemy extension in a Flask application:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:\/\/\/\/tmp\/test.db'\ndb = SQLAlchemy(app)\n\nclass User(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    username = db.Column(db.String(80), unique=True)\n    email = db.Column(db.String(120), unique=True)\n\n    def __init__(self, username, email):\n        self.username = username\n        self.email = email\n\n    def __repr__(self):\n        return '&lt;User %r&gt;' % self.username\n\n@app.route('\/')\ndef index():\n    user = User.query.first()\n    return 'Hello, ' + user.username\n\nif __name__ == '__main__':\n    db.create_all()\n    admin = User('admin', 'admin@example.com')\n    db.session.add(admin)\n    db.session.commit()\n    app.run()\n<\/pre>\n<p><span style=\"font-weight: 400\">In this example, we import the Flask module and create a Flask web server from the Flask module. We then import the SQLAlchemy extension and create an SQLAlchemy object that is bound to the Flask application. Also create a User model class that represents a user in the database, this class inherits from db.Model and has three fields id, username, and email. We define the routes of our application, in this example, the \/ route returns the username of the first user in the database.<\/span><\/p>\n<h4>5. WSGI compatibility<\/h4>\n<p>Flask is based on Werkzeug, which is a WSGI (Web Server Gateway Interface) utility library. This makes it compatible with any WSGI-compliant web server, such as Gunicorn or uWSGI.<\/p>\n<p>In Flask, WSGI (Web Server Gateway Interface) compatibility refers to the ability to run a Flask application on any WSGI-compliant web server.<\/p>\n<p>Here is an example of how to run a Flask application using Gunicorn:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># install Gunicorn\npip install gunicorn\n\n# run the application using gunicorn\ngunicorn --workers 4 --bind 0.0.0.0:8000 myapp:app\n<\/pre>\n<p><span style=\"font-weight: 400\">In this example, we are using the gunicorn command to run the Flask application. The &#8211;workers option is used to specify the number of worker processes to run, and the &#8211;bind option is used to specify the host and port to bind to. The myapp:app argument is used to specify the module and application object to run.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Here is an example of how to run a Flask application using uWSGI:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># install uWSGI\npip install uwsgi\n\n# create a uwsgi.ini file\n[uwsgi]\nhttp-timeout = 86400\n\nroute-host = ^(www\\.)?myapp\\. goto:myapp\nroute = .* last:\n\nroute-label = myapp\nroute-uri = ^\/([a-z]+)(?:\/(.*))?$ rewrite:\/myapp.py\/\\1\/\\2\nroute = .* last:\n<\/pre>\n<p>In this example, we are using the uwsgi command to run the Flask application. The uwsgi.ini file contains the configuration for uWSGI. In this example, we are routing the requests to the myapp.py file and specifying the routing using regular expressions.<\/p>\n<p>In both examples, the application will be served on the specified host and port and will be able to handle multiple requests simultaneously thanks to the WSGI compatibility.<br \/>\nIt&#8217;s worth noting that when running a production server you should use a proper web server like Nginx or Apache in front of your application to handle SSL, load balancing and other production-related tasks.<\/p>\n<h3>Conclusion<\/h3>\n<p>In conclusion, Python Flask is a micro web framework that makes it easy to build web applications. It offers a wide range of features that make it a popular choice for developers, such as routing, template rendering, form handling, support for extensions, and WSGI compatibility.<\/p>\n<p>Overall, Flask is a lightweight and flexible framework that is easy to learn and use, making it a great choice for small to medium-sized projects. Its unopinionated design allows developers to choose the tools and libraries that fit their needs, making it highly adaptable to a wide range of use cases.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python Flask is a microweb framework for Python that is used for building web applications. It is classified as a microframework because it does not require particular tools or libraries. It has a small&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":87320,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[4885],"class_list":["post-87024","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python-flask"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Amazing Facts About Python Flask - TechVidvan<\/title>\n<meta name=\"description\" content=\"Python Flask is a micro web framework for web applications. See its features like routing, template rendering, form handling etc.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Amazing Facts About Python Flask - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Python Flask is a micro web framework for web applications. See its features like routing, template rendering, form handling etc.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-03-23T05:19:15+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/03\/python-flask.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Amazing Facts About Python Flask - TechVidvan","description":"Python Flask is a micro web framework for web applications. See its features like routing, template rendering, form handling etc.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/","og_locale":"en_US","og_type":"article","og_title":"Amazing Facts About Python Flask - TechVidvan","og_description":"Python Flask is a micro web framework for web applications. See its features like routing, template rendering, form handling etc.","og_url":"https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2023-03-23T05:19:15+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/03\/python-flask.webp","type":"image\/webp"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Amazing Facts About Python Flask","datePublished":"2023-03-23T05:19:15+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/"},"wordCount":1260,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/03\/python-flask.webp","keywords":["Python Flask"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/","url":"https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/","name":"Amazing Facts About Python Flask - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/03\/python-flask.webp","datePublished":"2023-03-23T05:19:15+00:00","description":"Python Flask is a micro web framework for web applications. See its features like routing, template rendering, form handling etc.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/03\/python-flask.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/03\/python-flask.webp","width":1200,"height":628,"caption":"python flask"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/python-flask-facts\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Amazing Facts About Python Flask"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/87024","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=87024"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/87024\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/87320"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=87024"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=87024"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=87024"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}