create application folder
by console:
mkdir my-first-flask-app
initializate environment
inside the folder ...by console:
virtualenv env
set terminal to listen our environment
source env/bin/activate
then, the word «(env)» will appear at the beginning of the prompt
install flask with his dependencies
pip3 install Flask
at the end of the installing we can list the dependencies installed by:
pip3 freeze
it will show something like this:
click==8.0.1
dataclasses==0.8
Flask==2.0.1
importlib-metadata==4.6.3
itsdangerous==2.0.1
Jinja2==3.0.1
MarkupSafe==2.0.1
typing-extensions==3.10.0.0
Werkzeug==2.0.1
zipp==3.5.0
dataclasses==0.8
Flask==2.0.1
importlib-metadata==4.6.3
itsdangerous==2.0.1
Jinja2==3.0.1
MarkupSafe==2.0.1
typing-extensions==3.10.0.0
Werkzeug==2.0.1
zipp==3.5.0
creating our fist Flask app...
create a file called run.py and add this content:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
every Flask application extends from class Flask so we must create
a instance, in this case, called app with a parameter __name__ which is the name of the module.
route decorator tell us what function call by url
hello_world() for "/" in this example
the function must return what browser will show
"Hello, World"
Testing our application
we can use internal server to test our application, but before we must tell it which file it must call at the beginnig setting the environment variable FLASK_APP,
open and edit env/bin/activate file.
add at the end:
export FLASK_APP="run.py"
and save it.
To save this changes, we must going out from our environment
deactivate
and then, activate it again:
source env/bin/activate
now, we can start the internal server, like this:
flask run
* Serving Flask app 'run.py' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [05/Aug/2021 02:01:35] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [05/Aug/2021 02:01:35] "GET /favicon.ico HTTP/1.1" 404 -
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [05/Aug/2021 02:01:35] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [05/Aug/2021 02:01:35] "GET /favicon.ico HTTP/1.1" 404 -
open a browser and go to
http://127.0.0.1:5000
the browser will display
Hello, World!
by default, internal flask server listen to 5000 port
if we want to change it,
there are 2 ways:
- setting variable FLASK_RUN_PORT
or
writing the port at the end of the executing command, just like this:
flask run --port 6000
No hay comentarios:
Publicar un comentario