Fancy a quick intro to flask? Read on...
Note : You would need to know some basic python and a basic idea of what a webservice means
Why did i use anconda?
i am a data engineer (well sort off) so its easier for me to use it instead of the other python distributions, because i am more familiar with it.! Feel free to use your own d some of the notable distributions are found here
- From the splash menu or file menu click create new project. refer
- Give a name for the project. Example : flask_tutorial
- Its reacommended you setup the virtual enviornment by installing Flask.
- right click on the project name > new > python file
- give an name. Example : app.py
- write the following code in app.py
- After you write the code, you can use pycharms inbuilt terminal to run the code. You should see a 'Terminal' on the bottom bar.
- Type 'python app.py'
- Go to http://127.0.0.1:5000/hello and you should see the sentence "hello world" Yippe that was simple right ?
from flask import Flask
app = Flask(__name__)
@app.route("/hello")
def print_hello():
return "hello world"
if __name__== '__main__':
app.run(debug=True)
from flask import Flask
This is pretty simple, just like you import any module in python.
Python has special variables called dunder variables. Basically they are variables with trailing and leading double underscores.
You might have already know one, remember "__name__
", __main__
? There are many of them eg: __file__
Here we use it to let flask know where to look for templates, static files etc.
Here is a nice read up on dunder variables in python
For a nice intro to decorators see this youtube video by Corey. Please do check out his other videos. They are very easy to understand if you are new to python or even an expert!
Here @app.route("/hello")
tells flask to process the requests to localhost:5000/hello
to trigger our function, ie print_hello()
and generate the appropriate page.
app.run(debug=True)
This code will invoke your print_hello()
and also sets the debug mode to True. Its useful to see the way your code executes, but please refrain from using it in production.