Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,150,306 members, 7,808,037 topics. Date: Thursday, 25 April 2024 at 05:06 AM

Little drops of Python from a Flask: Learn Web Programming with Python - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Little drops of Python from a Flask: Learn Web Programming with Python (2718 Views)

Python From Zero To Hero... Full Video / Build A Bare Bones Reddit Clone With Python And Flask (hands On Tutorial Thread) / Pls Help With Python Problem (2) (3) (4)

(1) (Reply) (Go Down)

Little drops of Python from a Flask: Learn Web Programming with Python by pystar: 8:08pm On Oct 12, 2014
Prerequisites:
A UNIX based OS development machine
A UNIX terminal (I recommend finalterm)
or
Windows with Cygwin installed

Getting Started:
I do not like to install python libraries systemwide but create isolated Python environments where I can play around with any package I want without muddling up my System PATH. You can easily do this by installing virtualenv, read about this wonderful tool here http://virtualenv.readthedocs.org/en/latest/virtualenv.html and install it from here by running this command:
"pip install virtualenv"

Once that is done, kindly verify if it was successful by running this command:
"virtualenv --version"
You should get this as feedback "1.11.6" (latest version at time of writing)

To use the virtualenv to create an isolated Python environment, change into the directory you want the virtual environment to exist and kindly run this command:
"virtualenv [chosen_name_of_your_environment]"
Most programmers name their virtual environements "VENV" but you have the liberty to name it anything.
Your virtualenv would now have been created.

Now to get hacking, CD into the virtual environment you just created and run this command:
"source VENV/bin/activate" or ". VENV/bin/activate" kindly note the dot.
You would notice that your command line prompt would change to look something like this:
Example:
(venv)pystar@LogicLabsHQ --- where 'venv' is the name of my virtual environment, pystar is my username and logiclabsHQ is my machine name.
This is to show that your environment is now active.

To install Flask inside your virtual environment you just created, run this command:
"pip install flask"
To verify that flask has been installed, run this command:
"python"
"import flask"
If you can import flask successfully without tracebacks, then you are good to go.

So we are up and running. The next thing would be to create a hello world example app in flask

P.S: Do not include the quotation marks when running the indicated commands
Questions? quirks you dont understand? drop your comments here

2 Likes 3 Shares

Re: Little drops of Python from a Flask: Learn Web Programming with Python by pystar: 2:26am On Oct 13, 2014
Now, lets try to create the simplest app with flask. An app that says "Hello World"

I would assume that your virtual environment is still activated, you can confirm that by looking at your command prompt, the name of the environment must precede the prompt.

Change directory from the virtual environment folder and create another folder and move the virtual environment into it. Actually, this should have been done earlier, this folder would hold all your app files of which the virtual environment is one of them.
Run the following commands:
"cd .."
"mkdir drop_apps"
"mv -r venv drop_apps "
"cd drop_apps"
"mkdir app"
"cd app"


After running the above commands, you would have created an app folder that would hold all your app files including the virtual environment. Now lets quickly create our one file throw away example flask app.

Run the following commands:
"touch app.py"

Use a text editor to edit the newly create app.py file you just created and enter the following into the file:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
return 'Hello world'

if __name__ == "__main__":
app.run(debug=True)


Please note that nairaland doesnt maintain original source formatting, so kindly indent your code, even if mine doesnt seem indented.
To run the new code you just wrote, call up a terminal and run:
"python app.py"


Call up your browser and navigate to http://localhost:5000. Congratulations, if you ran everything as directed, you should have a simple HTML page showing "Hello World"

2 Likes

Re: Little drops of Python from a Flask: Learn Web Programming with Python by Nobody: 9:19am On Oct 13, 2014
Nice one Pystar... Am aspiring to be a Python Web dev... Though i heard Django or Web2py makes a lotta sense..
Re: Little drops of Python from a Flask: Learn Web Programming with Python by Nobody: 9:59am On Oct 13, 2014
.
Re: Little drops of Python from a Flask: Learn Web Programming with Python by Nobody: 10:07am On Oct 13, 2014
goon:
Flask is an extremely nice framework for web development in python. Ur only hiccups would come when you are trying to use flask-blueprint to structure your apps. My verdict is that for simple web applications that can be cooked up in a single script and do not require scaling to boost perfomance, Flask is good. In any other case, use Django.
What about Web2py.. Thats what am planning to use... The learning curve seems a bit easy... Any advice on this please? Thanks for your apt response...
Re: Little drops of Python from a Flask: Learn Web Programming with Python by Nobody: 12:08pm On Oct 13, 2014
.

1 Like

Re: Little drops of Python from a Flask: Learn Web Programming with Python by Nobody: 3:38pm On Oct 13, 2014
goon:
I don't know much about web2py but I think that it is also a good framework and has an active community of developers. It is also used by many websites, both commercial and personal. My personal suggestion would be to use micro-frameworks like Flask or web.py(not Web2py) for development as a newbie because you would learn a lot in the process that macro-frameworks like Django or Web2py abstract away from you. They would also expose you to a lot of less common features of python like decorators, property setters and getters, meta-classes e.t.c. Finally, choose one and start working with it rather than spend a lot of time thinking of the one to use. Cheers.
Thanks a lot bro.. Yo response is highly appreciated... I ll check out Flask n web.py and make a decision as to which of em suits my need.. Thanks Once again...
Re: Little drops of Python from a Flask: Learn Web Programming with Python by pystar: 11:54pm On Oct 13, 2014
Djangocode:
Nice one Pystar... Am aspiring to be a Python Web dev... Though i heard Django or Web2py makes a lotta sense..

I never could wrap my head around Django. It has too much upfront scaffolding and configurations to be made before you can even create anything.
I used web2py for 7 years before switching to Flask (which imho I feel is the spiritual successor to web.py). web2py is an awesome framework with an almost non existent learning curve with a vibrant community on google groups of which I was a constant contributor, but the only snag is that web2py holds your hand so much and does almost everything for you that in the end you dont really learn much about web development. Massimo is an awesome guy and a great programmer, but I just had to move on.

My humble advice is this, stick to web2py and have a broad but shallow knowledge about web development in Python or stick to flask and become a Ninja (you would learn so so much).
Re: Little drops of Python from a Flask: Learn Web Programming with Python by pystar: 11:57pm On Oct 13, 2014
goon:
Flask is an extremely nice framework for web development in python. Ur only hiccups would come when you are trying to use flask-blueprint to structure your apps. My verdict is that for simple web applications that can be cooked up in a single script and do not require scaling to boost perfomance, Flask is good. In any other case, use Django.
I disagree, you actually dont need to use blueprints in order to create large web apps in flask. I have a method I use which I would be showing in my 3rd installment. Django isnt too beginner friendly, it could be discouraging especially when the beginner is faced with so many new concepts and ideas to learn.

Stick to Flask. thanks
Re: Little drops of Python from a Flask: Learn Web Programming with Python by pystar: 11:59pm On Oct 13, 2014
goon:
I don't know much about web2py but I think that it is also a good framework and has an active community of developers. It is also used by many websites, both commercial and personal. My personal suggestion would be to use micro-frameworks like Flask or web.py(not Web2py) for development as a newbie because you would learn a lot in the process that macro-frameworks like Django or Web2py abstract away from you. They would also expose you to a lot of less common features of python like decorators, property setters and getters, meta-classes e.t.c. Finally, choose one and start working with it rather than spend a lot of time thinking of the one to use. Cheers.
You took those words out of my mouth. Stick to flask, web.py has stalled since Aaron Swartz died, also web.py documentation is sparse so you would be left to your own whims to figure stuff out.
Re: Little drops of Python from a Flask: Learn Web Programming with Python by pystar: 12:01am On Oct 14, 2014
Djangocode:
What about Web2py.. Thats what am planning to use... The learning curve seems a bit easy... Any advice on this please? Thanks for your apt response...
Flask or Web2py are both good. One is a microframework and the other is a full stack framework. Depending on your needs and requirements, you can choose any of the two. My money is on Flask
Re: Little drops of Python from a Flask: Learn Web Programming with Python by pystar: 6:28am On Oct 14, 2014
The 3rd installment should be out today but in the mean time, I am off to my sweat factory. See you in the evening
Re: Little drops of Python from a Flask: Learn Web Programming with Python by Nobody: 8:18am On Oct 14, 2014
pystar:


I never could wrap my head around Django. It has too much upfront scaffolding and configurations to be made before you can even create anything.
I used web2py for 7 years before switching to Flask (which imho I feel is the spiritual successor to web.py). web2py is an awesome framework with an almost non existent learning curve with a vibrant community on google groups of which I was a constant contributor, but the only snag is that web2py holds your hand so much and does almost everything for you that in the end you dont really learn much about web development. Massimo is an awesome guy and a great programmer, but I just had to move on.

My humble advice is this, stick to web2py and have a broad but shallow knowledge about web development in Python or stick to flask and become a Ninja (you would learn so so much).
Really good analysis... Thanks Boss...
Re: Little drops of Python from a Flask: Learn Web Programming with Python by Nobody: 8:32am On Oct 14, 2014
@Pystar For the benefit of Windows users like me, can u share the installation process on Windows...
Am planning to port to linux soon though!!!
Re: Little drops of Python from a Flask: Learn Web Programming with Python by Nobody: 11:51am On Oct 14, 2014
.
Re: Little drops of Python from a Flask: Learn Web Programming with Python by pystar: 7:26pm On Oct 14, 2014
Djangocode:
@Pystar For the benefit of Windows users like me, can u share the installation process on Windows...
Am planning to port to linux soon though!!!
I do not use Windows, but you can try out the procedure as described here:
http://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows

and after, run: "pip install flask"

There are 2 other options though:
1. As a Windows user who isnt completely ready to jump feet first into Linux (I wonder why) you can install virtualbox on your Windows PC and install a Linux OS within it as a guest. Hence you would have the awesome power of a UNIX based OS and the familiarity of Windows. You can then run all my commands without any issues.
2. Delete Windows OS and install a UNIX OS. #bliss

1 Like

Re: Little drops of Python from a Flask: Learn Web Programming with Python by Nobody: 1:45am On Oct 15, 2014
Thanks for the link bro..
My only fear is that my PC is an Old HP 530 with 80gb Hdd and 2.5gb RAM.. Using Vbox to run Both Linux and Windows might not be recommended since i have only like 34gb left...
Can Linux distros coexist with Windows on such minimal memory?
Re: Little drops of Python from a Flask: Learn Web Programming with Python by Nobody: 2:04am On Oct 15, 2014
..
Re: Little drops of Python from a Flask: Learn Web Programming with Python by Nobody: 8:22am On Oct 15, 2014
goon:
Yes. Use a lightweight distro like crunchbang or puppylinux. You would be fine...
Thanks Bro... You can go on with the tutorials...
Re: Little drops of Python from a Flask: Learn Web Programming with Python by 3Dimension: 10:51pm On Oct 15, 2014
A new follower..

Silently following
Re: Little drops of Python from a Flask: Learn Web Programming with Python by pystar: 4:52am On Oct 17, 2014
How to structure Flask apps

Single Module
A flask app with very few LOC can be put in a single file. Just like I did in the "hello world" example above. It can be used for quick, throw away programs

Example folder structure:

app/
venv/
templates/
static/
app.py
config.py
requirements.txt

App - Parent directory containing all app folders and files
venv - directory containing the virtual environment
templates - directory containing all view templates (i.e. HTML etc)
app.py - This is the main python file that defines the flask app. It holds the application logic.

Example of a simple app.py file (Kindly study this, we will be referring to it below)

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
return "hello world"

if __name__ == "__main__":
app.run(debug=True)


requirements.txt - is a file generated by running the command "pip freeze > requirements.txt". It is used to hold all installed flask extensions in the python app. It can be used to clone the app by running "pip install -r requirements.txt".
config.py - Holds the flask app configuration settings.

A Package
When your web app becomes larger, keeping everything in a single module can get messy and confusing. It would be more logical to split off everything in a group of interconnected modules i.e. a package.

Example:

app/
config.py
requirements.txt
run.py
instance/
config.py
app/
__init__.py
views.py
models.py
forms.py
static/
templates/

views.py - contains the business logic of your web app. Kindly dont confuse this with "view templates", those can be found in the templates folder. What you call "controllers" in other MVC python frameworks are called "views" in Flask ala Django.
forms.py - contains the form logic, here you define your form logic.
models.py - contains your database logic
__init__.py - this is the most important file in your app directory, as it acts as a glue to all the other app components like views.py, models.py etc. It imports them into its namespace and allows you to manipulate the app from there. The __init__.py replaces the "app.py" file that you defined in the single module app structure above.

Contents of the __init__.py file. Compare it with the app.py file as defined in the single module app structure as defined above.

from flask import Flask
app = Flask(__name__)

from app import views

Lets now dissect the __init__.py file
Line 1: we import the Flask class from the file module into our namespace as we did in the single module app structure above.
Line 2: An instance of the Flask class otherwise known as a Flask application instance was created and assigned to the app variable which acts as its handler.
Line 3: The directive "from app import views" doesnt not refer in anyway to the app variable we defined in Line 2. It actually refers to our package which we incidentally named "app" since its a python module, we are importing the views.py file contained within the app module into our working namespace so that we can have access to its properties. ***important***

views.py: As stated, this contains the routes and functions that get called by the route decorators. The views are the handlers that respond to requests from web browsers. In Flask views are written as Python functions. Each view function is mapped to one or more request URLs.
Example

from app import app

@app.route('/')
@app.route('/index')
def index():
return "Hello World"


Lets dissect the views.py file
Line 1: we are importing the flask application object which we instantiated in the __init__.py file and assigned to the app variable, into our namespace.
Line 2-5: This is a python decorator which wraps the index function. Whenever "http://url/" or "http://url/index" is entered into a browser bar, the index function would be called and "hello world" string would be returned.

run.py - is like the ignition of your web app. If you want to run your app you just "cd" into the app directory and run the command:
"python run.py"
example of a run.py file:

#!---PATH-TO-PYTHON-EXECUTABLE
from app import app
app.run(debug=True)


Lets dissect the run.py file:
Line 1: This is called the hash bang directive (for UNIX OS only). Its actually a directive thats used to make the run.py an executable by using a chmod +x on the file on the command line. Dont bother about it if you are on Windows.
Line 2: we are importing the flask application object which we instantiated in the __init__.py file and assigned to the app variable, into our namespace. Again.
Line 3: This line runs the app. Kindly leave out the "debug=True" directive when running your app in production. It isnt wise security wise to do so.

If you have really been following along and not just glazing over, you would have noticed something very important.
The app.py file created in the single module app has been split into 3 files in the package file structure:


app.py == __init__.py + views.py + run.py

This has actually made our app much more modular and this type of app structuring can be used to create apps of whatever size without using blueprints at all.
Re: Little drops of Python from a Flask: Learn Web Programming with Python by pystar: 6:36am On Oct 17, 2014
Off to my sweat factory. In our next session, I would be talking about templates, Jinja2, macros, etc.
Later. grin

1 Like

Re: Little drops of Python from a Flask: Learn Web Programming with Python by pystar: 9:47pm On Oct 17, 2014
Next up: Templates, Macros, Jinja2 et.al

1 Like

(1) (Reply)

I Saw This Nigerian Java/Python Instructor On UDEMY And It Made Me Happy / SIWES For Computer Science Students / Help With Biometric Identification System

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 58
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.