This article mainly introduces how to compile MVC configuration for the Python web framework to run it. The sample code is based on Python2.x. If you need it, refer to the following, the ORM framework, Web framework, and configuration are all ready. You can write the simplest MVC and start all of them.
With the @ decorator of the Web Framework and the Model of the ORM framework, you can easily compile a function to process the homepage URL:
# urls.pyfrom transwarp.web import get, viewfrom models import User, Blog, Comment@view('test_users.html')@get('/')def test_users(): users = User.find_all() return dict(users=users)
@ Viewthe specified template file is test_users.html. We created test_users.html under the templatesdirectory of the template:
Test users - Awesome Python Webapp All users {% for u in users %} {{ u.name }} / {{ u.email }}
{% endfor %}
Next, create a Web App startup file wsgiapp. py, initialize the database, initialize the Web framework, load urls. py, and finally start the Web Service:
# Wsgiapp. pyimport logging; logging. basicConfig (level = logging. INFO) import osfrom transwarp import dbfrom transwarp. web import WSGIApplication, Jinja2TemplateEnginefrom config import configs # initialize Database: db. create_engine (** configs. db) # create a WSGIApplication: wsgi = WSGIApplication (OS. path. dirname (OS. path. abspath (_ file _) # initialize the jinja2 template engine: template_engine = Jinja2TemplateEngine (OS. path. join (OS. path. dirname (OS. path. abspath (_ file _), 'templates') wsgi. template_engine = template_engine # load the URL Handler with @ get/@ post: import urlswsgi. add_module (urls) # Start the local test server on port 9000: if _ name _ = '_ main _': wsgi. run (1, 9000)
If everything goes well, use the command line to start the Web Server:
$ python wsgiapp.py
Then, access http: // localhost: 9000/in the browser /.
If there is no users table in the database, you will not be able to see the circular output content in the browser. You can add several records to the users table in the MySQL command line before accessing: