-
Notifications
You must be signed in to change notification settings - Fork 1
Microservices #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sm202073
wants to merge
3
commits into
main
Choose a base branch
from
microservices
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Microservices #13
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
--- | ||
title: Flask Ports | ||
|
||
date: 2022-09-20 | ||
|
||
authors: | ||
- smadha8 | ||
--- | ||
|
||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism-themes/1.9.0/prism-a11y-dark.min.css" integrity="sha512-bd1K4DEquIavX49RSZHIE0Ye6RFOVlGLhtGow9KDbLYqOd/ufhshkP0GoJoVR1jqj7FmOffvVIKuq1tcXlN9ZA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> | ||
|
||
# Default Port | ||
|
||
By default, Flask servers run on port 5000 or the local host in the main `app.py` file. However, the port can be changed or configured for back-end microservices or secondary microservices outside of the topmost hierarchical `app.py` Flask file. | ||
|
||
# Changing Ports | ||
Adding the `app.run` command in the main Flask app file can choose a different port to expose the microservice on. | ||
|
||
```python | ||
app.run(host='0.0.0.0', port=8080) | ||
``` | ||
|
||
The above command starts the web app on the local host at port 8080. | ||
|
||
# Adding Ports | ||
Adding microservices involve running them on separate ports so they can function together, or feed into a single middleware. | ||
|
||
For example, in an Flask application that uses the Courses Microservice, the microservice URL needs to be run separately by performing a `cd` into the relevant directory. Without the run command present as mentioned in the previous section, a `.env` file can be specified. | ||
|
||
|
||
For example, `.env` in the root directory of the project mentioned above can include the following line. | ||
``` | ||
COURSES_MICROSERVICE_URL="http://127.0.0.1:24000" | ||
``` | ||
|
||
Many microservices can have many different `.env` files, however they should all be on different ports. | ||
|
||
A subject microservice can be created with `.env` | ||
``` | ||
COURSES_MICROSERVICE_URL="http://127.0.0.1:24001" | ||
``` | ||
|
||
This URL can be accessed via a GET request in the main `app.py` using the requests library mentioned in the previous article. | ||
|
||
# Flask CLI Options | ||
Here are other config variables that can be added. | ||
|
||
FLASK_ENV - Controls the environment. | ||
FLASK_DEBUG - Enables debug mode. | ||
FLASK_RUN_EXTRA_FILES - A list of files that will be watched by the reloader in addition to the Python modules. | ||
FLASK_RUN_HOST - The host you want to bind your app to. | ||
FLASK_RUN_PORT - The port you want to use. | ||
FLASK_RUN_CERT - A certificate file for your app, so that it can be run with HTTPS. | ||
FLASK_RUN_KEY - The key file for your certificate. | ||
|
||
These options can also be indicated in the environment file. | ||
|
||
```python | ||
#.flaskenv | ||
FLASK_APP=demo | ||
FLASK_ENV=development | ||
FLASK_RUN_PORT=8080 | ||
``` | ||
|
||
# Virtual Environments | ||
Python projects live in virtual environments, however the user can specify virtual environments to avoid conflicts. | ||
|
||
For example if Project 1 needs 1.0 of Flask or a package such as PIL for reading images, and Project 2 needs version 2.0, installing these packages system-wide can interfere and cause package conflicts. | ||
|
||
Follow these steps in a terminal to create a virtual environment. | ||
|
||
```shell | ||
sudo apt-get install python3-venv | ||
``` | ||
|
||
You can create a project directory via | ||
```shell | ||
mkdir flaskexample | ||
cd flaskexample | ||
``` | ||
|
||
Creating a virtual environment within the project directory can be performed via a simple creation command to set the env to name 'venv.': | ||
|
||
```shell | ||
python3 -m venv venv | ||
``` | ||
|
||
Activating the virtual environment on Linux: | ||
|
||
```shell | ||
source venv/bin/activate | ||
``` | ||
|
||
and on Windows: | ||
|
||
```shell | ||
venv\Scripts\activate | ||
``` | ||
|
||
The following message should appear on the terminal | ||
|
||
```shell | ||
(venv) ➜ flaskexample | ||
``` | ||
|
||
|
||
|
||
## Further Reading | ||
|
||
https://flask.palletsprojects.com/en/2.2.x/config/ | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
--- | ||
title: Flask Requests | ||
|
||
date: 2022-09-20 | ||
|
||
authors: | ||
- smadha8 | ||
--- | ||
|
||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism-themes/1.9.0/prism-a11y-dark.min.css" integrity="sha512-bd1K4DEquIavX49RSZHIE0Ye6RFOVlGLhtGow9KDbLYqOd/ufhshkP0GoJoVR1jqj7FmOffvVIKuq1tcXlN9ZA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> | ||
|
||
# Making Web Requests | ||
|
||
Making HTTP requests is a core concept of networking, and Flask provides a built-in way to retrieve and post data to the browser. | ||
|
||
The requests library can be imported for use via | ||
|
||
```python | ||
from flask import Flask, request | ||
``` | ||
|
||
In order to use the requests library, the type of request must be specified in the route, for example | ||
|
||
```python | ||
@app.route('/login', methods='POST') | ||
def login(): | ||
error = None | ||
|
||
if valid_login(request.form['username'], | ||
request.form['password']): | ||
return "log_the_user_in", 200 | ||
else: | ||
error = 'Invalid username/password' | ||
|
||
``` | ||
|
||
The route above represents a POST request made through a form on the browser, where the data can be automatically accessed. | ||
|
||
Data posted can also be accessed via JSON. | ||
|
||
```python | ||
@app.route('/courseTime', methods='POST') | ||
def login(): | ||
request.json() | ||
course_time = request['course'] | ||
return course_time | ||
|
||
``` | ||
|
||
More than one request can also be handled at once. For example, one can respond differently to a GET and POST request. | ||
|
||
```python | ||
from flask import request | ||
|
||
@app.route('/', methods=['GET', 'POST']) | ||
def parse_request(): | ||
if request.method == 'POST' | ||
data = request.data | ||
# modify the data based on what is inputted | ||
return render_template('index.html') | ||
``` | ||
|
||
The attributes available on the request object (from the requests library) can involve unique ways of accessing the request body. | ||
|
||
## request.data | ||
Contains the incoming request data as string in case it came with a mimetype Flask does not handle. | ||
|
||
## request.args | ||
The key/value pairs in the URL query string. | ||
|
||
## request.form | ||
The key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encoded. | ||
|
||
|
||
## request.files | ||
The files in the body, which Flask keeps separate from form. HTML forms must use enctype=multipart/form-data or files will not be uploaded. | ||
|
||
## request.values | ||
Combined args and form, preferring args if keys overlap. | ||
|
||
## request.json | ||
Parsed JSON data. The request must have the application/json content type, or use request.get_json(force=True) to ignore the content type. | ||
All of these are MultiDict instances (except for json). You can access values using: | ||
|
||
request.form['name']: Use indexing if you know the key exists | ||
request.form.get('name'): Use get if the key might not exist | ||
request.form.getlist('name'): Use getlist if the key is sent multiple times and you want a list of values and only returns the first value. | ||
|
||
## Further Reading | ||
|
||
Request library documentation: https://tedboy.github.io/flask/generated/generated/flask.Request.html | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
--- | ||
title: Intro to Flask | ||
|
||
date: 2022-09-20 | ||
|
||
authors: | ||
- smadha8 | ||
--- | ||
|
||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism-themes/1.9.0/prism-a11y-dark.min.css" integrity="sha512-bd1K4DEquIavX49RSZHIE0Ye6RFOVlGLhtGow9KDbLYqOd/ufhshkP0GoJoVR1jqj7FmOffvVIKuq1tcXlN9ZA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> | ||
|
||
# Flask - An Introduction | ||
|
||
Flask is a lightweight Python server-side framework. It is known as a microframework becuase of it does not rely on external tools or programming languages in order to run. It is a WSGI (Web Server Gateway Interface) framework, an array of frameworks known to pass requests to web applications or frameworks. It is an intermediate step between front end and back end database structures. | ||
|
||
A Flask application is a very minimal built-in server web service, involving custom routes. Server-side microservices are the core of how programmers interact with API's by retreiving routes and how API's can be created. | ||
|
||
 | ||
|
||
Combined with the ease of learning Python, Flask is a great starting point for programmers looking to build web services quickly from the ground-up. | ||
|
||
```python | ||
from flask import Flask | ||
|
||
app = Flask(__name__) | ||
|
||
@app.route("/") | ||
def hello_world(): | ||
return "<p>Hello, World!</p>" | ||
``` | ||
|
||
The minimal Flask python file above is an example of user-defined routes. | ||
|
||
1. The first line imports the flask class for Python. | ||
2. Next, an instance of this flask class is created and stores it in the variable "app". | ||
**\_\_name\_\_** is a shorthand directive so Flask can locate Flask templates. | ||
3. The route() function gives Flask a direction to use a route. | ||
4. The function hello_world renders the message 'Hello World' to the browser when the '\/\' is retreived via a user GET request. | ||
|
||
User-specified paramters can also be extracted from the route. | ||
|
||
```python | ||
@app.route('/hello/<id>') | ||
def hello_with_id(id): | ||
return f"hello {id}!" | ||
``` | ||
|
||
|
||
|
||
## Compiling and running Flask microservices | ||
|
||
```python | ||
pip install Flask | ||
``` | ||
|
||
To run the Flask application, | ||
|
||
```python | ||
python -m flask run | ||
``` | ||
|
||
This command will run on a local browser. | ||
To run it on an externally visible port with public IP's, use | ||
|
||
```python | ||
flask run --host=0.0.0.0 | ||
``` | ||
|
||
To run with specific flags, the flags can be added to the run command. A useful flag for developing is | ||
|
||
```python | ||
python --app {app name} --debug run | ||
``` | ||
|
||
## Further Reading | ||
|
||
Flask documentation is very organized: | ||
https://flask.palletsprojects.com/en/2.2.x/quickstart/ | ||
|
||
The next articles will delve on tutorials on how to implement useful functionality in Flask. |
Empty file.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.