Why would you want to build a website using python with no framework here is some reasons :
- you want to understand how this flask , django works
- want to build your own framework in the future
- you like to build things from scratch
writing a simple python website without a framework is easy if you just want some basics features,
but if you want more advanced features like routing, database connection, validate forms, and add your own template engine then things will become difficult bit by bit
Requirements
requirements or what you need to know before you can start doing this
-
a basic knowledge about http protocol, this is some resources if you want to learn more about how http work :
-
what WSGI is? , some resources if you want to know :
An Introduction to the Python Web Server Gateway Interface how to serve a python web app using something like gunicorn , gevent
A simple hello World
here a simple example of a hello web python application
def app(environ, start_fn):
start_fn('200 OK', [('Content-Type', 'text/plain')])
return ["Hello World!\n"]
but how to run this ? , first we need to install gunicorn or gevent or something similar, for me i choose gevent because gunicorn will not work with windows.
Installing genvent
pip install gevent
Running the app
we need to import the gevent wsgi class to serve the app
....
if __name__ == '__main__':
from gevent.pywsgi import WSGIServer
WSGIServer(('', 8000),app, spawn=None).serve_forever()
want to know why we use
if __name__ == '__main__':
check this stackoverflow answer by Jack
our code will look like this now
def app(environ, start_response):
data = b"Hello, Web!\n"
start_response("200 OK", [
("Content-Type", "text/plain"),
("Content-Length", str(len(data)))
])
return iter([data])
if __name__ == '__main__':
from gevent.pywsgi import WSGIServer
WSGIServer(('', 8000),app, spawn=None).serve_forever()
now you can go to your terminal and run
python app.py
check localhost:8000 and you will see a hello web message in your favorite web browser
in the next part, we will write a code to render an html file, create multiple pages, and navigate between them.
For Further Exploration
How to write a Python web framework
Python Web Applications: The basics of WSGI
How to use Flask with gevent (uWSGI and Gunicorn editions)
Simple Python Framework from Scratch
Top comments (0)