Python -- flask, pythonflask
Flask is a lightweight Web application framework written in Python.
Next I will use the Flask framework to create a simple html page example.
1. Create the website root directory exweb
Mkdir exweb
2. create a virtual environment under the root directory of the website. The virtual environment is a copy of the main python. The advantage is that you can only install the flask package to this virtual directory, and your main python will not be affected, another benefit is that you do not need to have root permissions.
Cd exweb
Virtualenv uniqueenv
3. Install flask
Uniqueenv/bin/pip install flask
4. Use flask. The app. py code is as follows:
#-*-Coding: UTF-8-*-from flask import Flask, render_template, requestfrom flask. ext. wtf import Formfrom wtforms import TextField, BooleanField, TextAreaFieldfrom wtforms. validators import Required, Lengthapp = Flask (_ name _) # The CSRF_ENABLED configuration is used to activate the Cross-Site Request Forgery protection app. config ['csrf _ enabled'] = Trueapp. config ['secret _ key'] = 'xxx' # form class HelloForm (Form): name = TextField ('name', validators = [Required ()]) Greet = TextField ('greet ', validators = [Required ()]) @ app. route ('/', methods = ['get', 'post']) def index (): # submit in GET mode. If the url parameter is not empty, directly jump to the display Page name = request. args. get ('name') greet = request. args. get ('greet ') if name! = ''And name! = None and greet! = ''And greet! = None: greeting = "% s, % s" % (name, greet) return render_template('index.html ', title = u'display info', greeting = greeting) # Otherwise, the form is submitted in post mode and jumps to the input information interface form = HelloForm () if form. validate_on_submit (): greeting = "% s, % s" % (form. name. data, form. greet. data) return render_template('index.html ', title = u'display info', greeting = greeting) return render_template('hello_form.html', title = u'input info', form = form) app. run (debug = True)
5. in the previous step, we imported a new function named render_template from the Flask framework. Internally, render_template calls the Jinja2 template engine, jinja2 will replace {...} with the corresponding values provided by the template parameters {{...}} block.
The template is placed in the templates folder.
Mkdir templates
First, create a basic template page base.html
Hello_form.html
{% extends "base.html" %} {% block content %}
Index.html
{% extends "base.html" %} {% block content %}{%if greeting:%} I just wanted to say <em style="color:green;font-size:2em;">{{greeting}}</em>{%endif%}{% endblock %}
7. the directory structure of the project is as follows:
Exweb \
Uniqueenv \
App. py
Templates \
Base.html
Hello_form.html
Index.html
8. Run: uniqueenv/bin/python app. py
Note that the python interpreter in the virtual directory should be used during running.
9. Results:
(1) Get Method
(2) Post Method