₦airaland Forum

Welcome, Guest: RegisterLoginWith GoogleTrendingRecentNew

Stats: 3,325,041 members, 8,420,023 topics. Date: Thursday, 04 June 2026 at 09:44 AM

Toggle theme

Pystar's Posts

Nairaland ForumPystar's ProfilePystar's Posts

1 2 3 4 5 6 7 8 9 (of 9 pages)

ProgrammingRe: Build A Bare Bones Reddit Clone With Python And Flask (hands On Tutorial Thread) by pystar(op): 9:11am On Nov 12, 2014
Ajibel:
This tutorial already exists!!
Where?
ProgrammingRe: Build A Bare Bones Reddit Clone With Python And Flask (hands On Tutorial Thread) by pystar(op): 9:10am On Nov 12, 2014
Another flask tutorial of mine has taken precedence over this. Kindly check.
Technology MarketRe: US Used Lenovo Thinkpad T430s Laptop For Sale. by pystar: 6:41am On Nov 03, 2014
eliascomm55:
the screen size is 14inches. No issue at all, I can let it go for 55k.
40k and you get your money today. IF you are ready send me a PM.
Does it have a back lit key board?
Technology MarketRe: US Used Lenovo Thinkpad T430s Laptop For Sale. by pystar: 4:52am On Nov 03, 2014
Serious buyer here.
Whats the screen size?
Are there any issues with the laptop that you would like to disclose here?
Can you let it go for 40k?
ProgrammingRe: How Many Mb's Will It Cost To Download Python by pystar: 12:35am On Oct 19, 2014
adexsimply:
But the question he posed is correct... How many megabytes will it...using MB in this context is not wrong.
semantics, its correct. syntax, its wrong.
Technology MarketRe: Scuit: Shop & Ship From China, USA, Dubai & UK (Express, Cargo & Shipping) by pystar: 9:23pm On Oct 18, 2014
ultimate2010:
sir why can't my items ship on sunday and what's the full meaning of ETA thanks.
Expected Time of Arrival
ProgrammingRe: Little drops of Python from a Flask: Learn Web Programming with Python by pystar(op): 9:47pm On Oct 17, 2014
Next up: Templates, Macros, Jinja2 et.al
ProgrammingRe: Little drops of Python from a Flask: Learn Web Programming with Python by pystar(op): 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
ProgrammingRe: Little drops of Python from a Flask: Learn Web Programming with Python by pystar(op):
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.
ProgrammingRe: How Many Mb's Will It Cost To Download Python by pystar: 4:05am On Oct 17, 2014
I really cant get why Nigerian's call their data allocation "MB". Data is data, for the love of god dont call it mb. MB is just a unit of measurement.
Technology MarketRe: Scuit: Shop & Ship From China, USA, Dubai & UK (Express, Cargo & Shipping) by pystar: 8:47pm On Oct 15, 2014
Whats the ETA of an item you buy from aliexpress to land in Lagos?
ProgrammingRe: Little drops of Python from a Flask: Learn Web Programming with Python by pystar(op): 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
ProgrammingRe: Little drops of Python from a Flask: Learn Web Programming with Python by pystar(op): 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
ProgrammingRe: Little drops of Python from a Flask: Learn Web Programming with Python by pystar(op): 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
ProgrammingRe: Little drops of Python from a Flask: Learn Web Programming with Python by pystar(op): 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.
ProgrammingRe: Little drops of Python from a Flask: Learn Web Programming with Python by pystar(op): 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
ProgrammingRe: Little drops of Python from a Flask: Learn Web Programming with Python by pystar(op): 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).
Technology MarketRe: Laptop Screen Replacement At Reduced Price in Nigeria. by pystar: 7:15pm On Oct 13, 2014
neupert:
We have your lenovo b570e laptop screen and we can fix it for you at 14k.
How soon do want to fix it?
You can reach on 08124461809.
#9k
ProgrammingRe: Little drops of Python from a Flask: Learn Web Programming with Python by pystar(op): 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"
Technology MarketRe: Laptop Screen Replacement At Reduced Price in Nigeria. by pystar: 8:20pm On Oct 12, 2014
lenovo b570e screen.
ProgrammingLittle drops of Python from a Flask: Learn Web Programming with Python by pystar(op):
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
ProgrammingRe: Build A Bare Bones Reddit Clone With Python And Flask (hands On Tutorial Thread) by pystar(op): 7:32pm On Sep 18, 2014
jajad: pystar, this tutrial has stalled. sad
Work ish and discovering Neo4j took me away. ***In Arnold Schwazeneggers voice*** I will be back
EducationRe: Why You Must Finish With At Least A 2.1 by pystar: 3:20pm On Sep 11, 2014
2.1 or higher is good, being self reliant is better. The owner of nairaland didn't even graduate, yet we are here......
CelebritiesRe: Celebrities Who Look Much Older Than Their Age ( Photos ) by pystar: 7:35pm On Sep 08, 2014
lalasticlala: Bryan okwara

toolz

Flavour
flavours legs though!!! Your trainer should up his game, this Johnny bravo look ain't cool.
CelebritiesRe: Denrele Retweets Nairaland Tweet Concerning Him On Twitter by pystar: 4:23pm On Aug 30, 2014
MissMeiya: I feel like I'm stalking you. I've run into you on yet another social medium. Can you guess? Don't say my name though.

Edit: Haha, I just realized something... Nvm. You won't know. embarassed
Insi--- I know you ---dious
PoliticsRe: My Experience With SARS Operatives In Ibadan; Another SOKA In The Making! by pystar: 4:21pm On Aug 30, 2014
Leetunechi: guy. When you wan buy some sence undecided ?
Like the "sence" you have for sale?
CelebritiesRe: Denrele Retweets Nairaland Tweet Concerning Him On Twitter by pystar: 11:51am On Aug 30, 2014
Briareos: So, lemme get this straight... Nairaland wrote about Derenle. Derenle now tweets what Nairaland wrote about him. Now, Nairaland writes about Derenle's tweet about what Nairaland wrote about him?

So, soon, Derenle will again tweet what Nairaland wrote about him tweeting what Nairaland wrote about him in the first place.
INCEPTION
ProgrammingRe: HOWTO: Create A Simple API With Python And Flask by pystar(op): 4:56am On Aug 29, 2014
You can copy the above code into a file and name it api.py, kindly indent it to enable it run. Ensure you have installed the flask-restful extension into your flask installation (hopefully you should be using virtualenv).

Run the app with
$ python api.py and visit http://localhost:5000/api/v1.0 to see the api in action.

To view the API returned data programmatically
$ curl -i http://localhost:5000/api/v1.0

In my next post, I will show how to post data with the API. (Off to work grin)
ProgrammingHOWTO: Create A Simple API With Python And Flask by pystar(op): 4:51am On Aug 29, 2014
This is a simple flask app: Pardon the lack of indentation in my code.
Installing Flask-Restful in your flask app makes building API's extremely simple.

$ PIP install flask-restful

######Simple flask app with API to expose the app##########

from flask import Flask
from flask.ext.restful import Resource, API

app = Flask(__name__)
api = Api(app)

@app.route("/" )
@app.route("/index" )
@app.route("/home" )
def index():
return "Returning data"

###This exposes your app as an API###

class Nairaland(Resource):
def get(self):
return {"data" : "Returning data"}

app.add_resource(Nairaland, "/api/v1.0/" )

if __name__ == "__main__":
app.run()
PoliticsRe: My Experience With SARS Operatives In Ibadan; Another SOKA In The Making! by pystar: 10:18pm On Aug 28, 2014
.
AutosRe: Preorder System For Powerbikes Needed. by pystar(op): 3:40am On Aug 23, 2014
bump bump
AutosRe: Preorder System For Powerbikes Needed. by pystar(op): 9:42pm On Aug 18, 2014
bump

1 2 3 4 5 6 7 8 9 (of 9 pages)