Python Show-Me-the-Code 0,023rd question Web guestbook application, pythoncode
Question 0,023rd:Use the Python Web framework to create a Web version message book application.
What are the Web frameworks of Python?
Ideas:
Flask is a lightweight Web application framework written in Python.
This application uses Flask in the background and mongodb in the database. Previously I used Tornado to write a similar one, so I tried to use Flask. Write the style and template at the front end to render the data returned from the back end. If you leave a message, submit it to the backend and store it in mongodb. Because this application is relatively simple, the flask Lightweight Framework is suitable for mongodb and is easy to use.
Code:
Only the py file is provided here.
Complete code can be found at: github address
Run. py
from flask import Flask, request, render_template, url_forimport pymongoimport datetimeapp = Flask(__name__)# database settingmongoClient = pymongo.MongoClient('localhost',27017) db = mongoClient['msgboard']# conn = pymongo.Connection('localhost',27017)# msgboard = conn.msgboard# msgboard.create_collection('msg')@app.route('/', methods=['GET', 'POST'])def index(): if request.method == 'GET': return render_template('index.html', msglist=db['msg'].find()) else: msg_collection = db['msg'] time = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S') msg_collection.insert({ 'msg': request.form['msg'], 'time': time }) return render_template('index.html', msglist=db['msg'].find())if __name__ == '__main__': app.run(debug=True)
Running effect: