2026-08-28 17:51
Status:
Tags: Flask IBM IBM Full Stack Software Developer Professional Certificate IBM - Developing AI Applications with Python & Flask AI Web Development Python Full Stack Back End Frameworks
DAAPF - Module 2 - Web App Development Using Flash
==Web App Deployment using Flask
-
Python Libraries and Frameworks for Application Development:
- Python Libraries are basically tool kits that you can import into your own code in order to expedite the process where in which you try and produce something
- They are great because they speed up the work flow, and make it very easy for you to write the code you want without a ton of boiler plate
- A bunch of good python libs are
NumPy (Mathemcatical Calculations), Pandas (Data manipulation and analysis), and Matplotlib (Data Visualization) - Python Libraries for app dev, things like
requests and BeautifulSoupwhich make it very easy for you to handle things like HTTP requests and even scrap web pages for their given content SQLAlchemyis a library that is focused around the SQL toolkit and allows you to handle things like working with an SQL data base in whatever language you are inPyTestis a testing framework that lets you create small and simple tests, but also scales upwards as well- Frameworks are pre-defined structures for application development that provide a set of guidelines for said development
- They facilitate good coding practices by giving a skeletal structure of how your base line code interacts that determines how your application behaves, and therefore allows you to have a faster development process
- Some python ones are
Django, Web2py, & Flask
- Some python ones are
-
Introduction to Flask:
-
Flask- it is a micro web framework that can be used to create small web applications, and is not opinionated like some other larger frameworks
-
It does not work like a regular framework, and does not bind the developer to a certain set of tools
-
Flask 2.2. 2 runs on Python 3.7 and newer, so it does not run on anything false
-
It was created in 2004 by Armin Ronacher as an April fools joke, but quickly gained a ton of attention for it’s minimal set of dependencies
-
It also has a large amount of community-maintained extensions
-
Main Features
- It has a built-in web server that allows you to run and listen in to requests, similar to how something like node might work, but instead with python
- It has debugger that shows interact trace-back and stack trace in the browser for your given web application
- It has the standard Python Logging method, which makes it very easy to integrate with custom messages or tools
- It also has built in unit testing which gives the framework a test driven approach, and therefore makes it very simple for you to integrate other libraries like
PyTestor whatever the fuck in the above - It enables the
request & responseobjects like node does as well, and generally lets you treat them as objects with the data operations you would need on them
-
Additional features
- It provides support for static assets like
.css .js and imageswhich allows you to load these in statically - You can even provide dynamic templates using outside frameworks, which can change for each request
- It supports routing and dynamic URLs with HTTP methods, allowing for things like redirection of the user
- It also has good error handling if you would need to use that
- It also supports user sessions
- It provides support for static assets like
-
Popular Community Extensions-
Flask-SQLAlchemygives support for SQL to flask, letting users work with databases inside of pythonFlask-Mailallows you to set up ansmtpmail transfer server for sending out emails and what notFlask-Adminlets you add admin interfaces to flask interfaces very easilyFlask-Uploadsallows you to handle custom file uploads to your application very easily as well
-
Flask CORS allows for flask to have cross origin resource sharing between two applications
-
Flask-Migrate adds in the ability to migrate different sql databases, as a support to the above hand alchemy library
-
-
You can install task using something like
piphowever, if you are installing it on your machine, it is recommended you using something like avenvor a virtual environment before you actually set it up as to not have issues with things like different dependencies and what not -
-
Above is how to check out all dependencies for something like flask
-
Flask Built-in dependencies
Werkzeug:implements server capabilitiesJinja:a template language that renders you application i guessMarkupSafe:providers security features in templates, this comes with Jinja and is used to help against SQL injection attacksItsDangerous:is a signing library for session cookies, letting you see if your data has been messed withClick:helps write command line interfaces for Flask, and lets you add in things like custom commands
-
-
-
Deploying Web Apps using Flask:
-
Flask as said is a micro-framework that is used for creating web applications with python, it is very flexible, extensible, and easy to use and implement
-
It supports CRUD (Create Read Update Delete) requests using POST and GET HTTP requests from some client or something
-
-
The above hand images has the flask logo as well as the given HTTP method that would then correspond with the given CRUD operation
-
Creating A Web Application with Flask
- Install Flask using
pip install Flaskwhich install the flask package in your given environment, it is recommended to do this inside of avenvor virtual environment however - Import the flask package inside of your code and what not
- Instantiate that exact same flask package so you have a flask object,
- Create the application
- Run the application
- Install Flask using
-
Hello World Application: An Example
-
-
This loops basically really similar to something you would find using something like node here basically
-
You first import the given Flask object from the main Flask framework, as which point you create an application object using that flask function
-
Then, on a given route that you would decide, you have a function that would run code whenever you have someone access the application at that given route, running that code
-
At the bottom then you have the main start up of the given application, although in the above hand example the only two things that are really different from node are the fact that the port number is not specified, and there is also no direct handling of something like an HTTP POST or GET request like you might find in a node app
-
This does in fact respond to a GET request though, let it be known, you can generally specify the method GET or POST inside of Flask, but if you do not like it is in the example, the default call is GET
-
-
You can start the server by saving the code inside of a python file and then running it just like any other application that you might have
-
When the web application server starts, IT GIVES YOU THE IP ADDRESS AND PORT that the web application is listening on
-
You can check the endpoints by connecting to them on a browser
-
Templates are pre-created HTML pages that are served from the web application, they are able to be either static or dynamic, and by default looked for in a directory called
templatesunder the root directory -
If they need to use things like image or css files or something like that, those would be stored in a
staticdirectory also in the root directory -
-
Basically, you have the standard get up that you might see inside of a web application with the whole get and post and all of that, this time specified
-
You then also import things like
render_template & requestfrom the flask framework -
Then, whenever you want to render a given template that might exist inside of your templates directory, you have a
render_templatemethod that is ran on a specific route, and then you call that render_template function with a path to whatever static or dynamic page it is that you want to draw -
If you want to draw dynamic html pages, you can also do so by passing in arguments to the given render_template code
-
-
Decorators in Flask:
-
Flask - Basic Applications and Routes:
-
PROJECT STRUCTURE
-
-
-
-
Basically, you set up the application using the steps talked about above right, and then whenever you want to add in a new route or a new endpoint for your given API, you would then use the
@app.rout('/')decorator -
A decorator inside of python is basically just a way of calling a function over another function, letting you manipulate what does inside of it. Basically, think of it as whenever you pass in an arrow function inside of a larger function inside of node, the decorator is basically that larger function you are passing your own code into
-
There, you would do things like specify the URL endpoint for you to handle using python, as well as then also specify if this is a POST or a GET or whatever other HTTP request you want to handle
-
-
You need to set up the flask variables with whatever you have like your code that you wrote or the development environment tag or something like that
-
These feel similar to something like the export modules inside of node where you basically just use export as a means of giving out whatever data you want from this file
-
-
Generally you have an open port on 5000 using flask, though I assume there has to be a way to change that, but you can then also see the console output for the given URL requests at specific routes that you might have which would then allow you to see the above hand information on your request
-
-
Returning JSON from your given application
- This can be done by returning a serializable type object from your application like a dictionary or a list which very cleanly go into JSON objects
- You can use the
jsonify()method provided by flask, which takes in key value pairs, and returns the given json to the client, basically allowing you to have a variable and then what it equals, allowingjsonifyto then basically make it into a JSON response
-
-
ENVbasically indicates the environment production, or development, that the application is running in -
Debuglets you use the debug features of flask -
Testing, similar to debug, lets you run the test mode of the flask framework -
Secert_Keylets you assign a session cookie -
Session _cookie_ nameis the name of the session cookie -
Server_namefinds the host and port of your server -
Jsonify_mimetypewill have your thing default to application/json content type -
-
Config object is also something that is provided by flask and lets you programmically change the configuration inside of your given code by updating this object with whatever you have
-
this i figure would be pretty good for things like automatic keys and what not or secret keys and such IDK
-
-
Requests and Response Objects - Using GET and POST Modes:
-
Custom Routes whenever you have something like
@app.route("/path")decorator would default to the standard GET method, however, you can add in a@app.route("/path", methods=["GET"])to change out the specific HTTP request to be listening out for -
The two lines of code above are basically the same btw, they do the same things, but you can change out the GET for other things in order to handle different inputs and responses, you can even do more than a single one like so:
-
-
Request Object: Attributes
-
All HTTP calls to Flask contain the request object created from the Flask. Request class
-
Whenever someone requests a resource from the flask server, it is handled by the
@app.routedecorator, and you can examine and explore the request object in the same method, the following image for the common request object attributes -
-
-
The above hand image is basically some of the stuff printed out on the client side and what not, and it showcases some of the basic data like the server ip, the given headers passed in the request, and some of the actual request object data too like the path and attributes, this is available in both the back end and front end
-
-
Request Object: Methods
get_dataget the POST data from the request as bytes, which YOU are then responsible for managing and parsing itget_jsonwhich lets you get the POST data from the request but already parsed as a JSON object
-
-
If you want to actually access values from any one of the above mentioned methods, what you can actually do is index them the say way that you would a given python dictionary, and then using that indexed item, you can then say get whatever data it is that you want to
-
The data is basically stored in a way that is similar to a python dictionary, so you can index it the same way
-
This would also then basically allow you to deconstruct the above hand URL using the above hand code as well using the get method, notice that the
getmethod is a function and not an index, and will only return a null object if it does not find the right thing, while the index method will crash the server -
Response Object: Attributes and other stuff
-
-
basically the response object that would exist inside of any real back-end framework, this is the thing that would send the response back over to the front-end for processing, and Flask also has a built in library object that you can use for this as well, the above hand image shows some attributes of the response object
-
-
Dynamic Routes:
- Calling External APIs, the easiest way to use this is to the external
requestslibrary from python, which allows you to return JSON as a dictionary to the caller - In the above hand example, you would import the
Flaskframework as well as therequestslibrary - After doing so, you basically set up your basic route with flask and what not, the regular stuff
- Then, you would use
requeststo basically send a get HTTP request over to your given API endpoint from whatever database you might have in order to recieve whatever data it is that you might need - This would then basically load in the data for you from the given response at that endpoint, giving you whatever data you have letting you manipulate it however you would like, whether that be JSON or something else
- Dynamic route parameters
- Say you want to develop a RESTful API that requires a resource ID in the Url to query for some specific item like a given book or something like that
- Instead of doing something like
http://localhost/book/1449355730and hard-coding in the specific id of that book, instead what you can do is have the client send it as part of the URL - In the above hand example, you can basically get whatever information you would want inside of the function
- The first 2 lines get the
isbnfrom the client sending in a request at that given end point - You snatch over the ID or whatever other parameter from that client side route and then you use it in order to pass that ID value into your database query for whatever external API you are connecting to
- Calling External APIs, the easiest way to use this is to the external
-
Error Handling:
- HTTP status code stuff
- Flask Server automatically returns 200 status by default when a string or a dict is returned, so you do not need to manually do it
- It is also returned by
jsonify(), making it very easy to use - You can generally specify a specific code that you would want to send instead of the regular default one, which you do by
- Returning a tuple with the response as the first value, and then the status as the second value
-
Additional Features in Flask:
==Summary
- Python libraries are like toolkits. Each library has specific tools to simplify and expedite certain programming tasks. Frameworks are predefined structures for application development. Framework enables you to build the complete application, while libraries aid with specific functionality.
- Flask is a microframework that ships with minimal dependencies. To build websites, Flask has features like debugging servers, routing, templates, and error handling. Flask can be installed as a python package. Django is a full-stack framework compared to Flask. You can create a server by instantiating the Flask class.
- Flask provides a Request and a Response object for each client call. You can get additional information from the Flask Request, like headers. You can parse the Request Object to get query parameters, body, and other arguments. You can even set status on Response objects before sending a response back to the client.
- You can use dynamic routes to create RESTful endpoints.
- There are multiple classes of HTTP status codes showing success, user error, or server error. Flask implicitly returns a success code of 200 with the response. You can also provide status codes explicitly. Flask also provides application-level error handlers.
- Flask is a microframework for creating web applications and supports CRUD.
- Install the Flask package using pip.
- To create a web application using Flask:
- Import Flask
- Instantiate Flask
- Run the app
- You can render both static and dynamic templates with Flask.
==Cheat sheet
| Package/Method | Description | Code Example |
|---|---|---|
| Flask | Used to instantiate an object of the Flask class named app. | python from flask import Flask app = Flask(__name__) |
| @app.route decorator | A decorator in Flask used to map URLs to specific functions in a Flask application. | python @app.route('/') def hello_world(): return "My first Flask application in action!" |
| 200 OK status | Flask servers automatically return a 200 OK status when you return from the @app.route method. 200 is also returned by default when you use the jsonify() method to respond to a request. A successful response with a status code of 200 will be sent back when the given code executes. | python @app.route('/') def hello_world(): return ("My first Flask application in action!", 200) |
| HTTP Client Error Codes (4xx) | 400 indicates an invalid request. This status could imply the parameters are missing or improper or the request is invalid in another way. 401 indicates the credentials are missing or invalid. 403 implies that the client credentials are not sufficient to fulfill the request. 404 If the server is unable to find the resource, it returns a 404 status. 405 Method Not Allowed indicates that the HTTP method used for the request is not supported for the requested resource. 422 indicates that the server understands the request but cannot process the content because it is semantically invalid. | python @app.route('/') def search_response(): query = request.args.get("q") if not query: return {"error_message": "Input parameter missing"}, 422 # fetch the resource from the database resource = fetch_from_database(query) if resource: return {"message": resource} else: return {"error_message": "Resource not found"}, 404 |
| Error 500 | 500 is used when there is an error on the server. | python @app.errorhandler(500) def server_error(error): return {"message": "Something went wrong on the server"}, 500 |































