python + flask + sqlite3做一个小博客 |
您所在的位置:网站首页 › flask配置数据库 › python + flask + sqlite3做一个小博客 |
背景:最近刚学习完python的基本语法,就迫不及待想去做一些小项目。由于我是做前端的,对服务器比较感兴趣,就寻思着做一个后台服务。正好有个flask框架可以学习一下。Flask官方文档 (官方文档上还是有许多坑的,不过通读一遍还是能学习到很东西) 1、代码结构 /flaskr /templates lay_out.html login.html show_entries.html /static flaskr.py schema.sql/templates文件夹,放置模版、/static放静态资源(css,js)、schema.aql 为sqllite数据库模式配置文件 2、先贴代码 算了,先配置虚拟环境吧(windows 操作系统下) 安装 virtualenv pip install virtualenv 创建 venv 虚拟环境 $ cd flaskr $ virtualenv venv New python executable in venv/bin/python Installing distribute............done.
激活虚拟环境(激活必须是cmd 超级管理员模式下激活) venv\scripts\activate激活后的效果(路径前面有"venv") 这时 运行python(导入flask,不报错即为成功) >> from flask import Flask 3、贴代码了: # flaskr.py # all the imports from __future__ import with_statement from contextlib import closing # contextlib.closing()会帮它加上__enter__()和__exit__(),使其满足with的条件。 import sqlite3 import time from flask import Flask, request, session, g, redirect, url_for, \ abort, render_template, flash # configuration DATABASE = './flaskr.db' DEBUG = True SECRET_KEY = 'development key' USERNAME = '1' PASSWORD = '1' app = Flask(__name__) app.config.from_object(__name__) app.config.from_envvar('FLASKR_SETTINGS', silent=True) def connect_db(): return sqlite3.connect(app.config['DATABASE']) def init_db(): with closing(connect_db()) as db: with app.open_resource('schema.sql') as f: db.cursor().executescript(f.read()) db.commit() @app.before_request def before_request(): g.db = connect_db() @app.after_request def after_request(response): g.db.close() return response @app.route('/') def show_entries(): cur = g.db.execute('select title, text from entries order by id desc') entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()] return render_template('show_entries.html', entries=entries) @app.route('/add', methods=['POST']) def add_entry(): if not session.get('logged_in'): abort(401) g.db.execute('insert into entries (title, text) values (?, ?)', [request.form['title'], request.form['text']]) g.db.commit() flash('New entry was successfully posted') return redirect(url_for('show_entries')) @app.route('/login', methods=['GET', 'POST']) def login(): error = None if requesthod == 'POST': if request.form['username'] != app.config['USERNAME']: error = 'Invalid username' elif request.form['password'] != app.config['PASSWORD']: error = 'Invalid password' else: session['logged_in'] = True flash('You were logged in') return redirect(url_for('show_entries')) return render_template('login.html', error=error) @app.route('/logout') def logout(): session.pop('logged_in', None) flash('You were logged out') return redirect(url_for('show_entries')) if __name__ == '__main__': app.run()schema.sql drop table if exists entries; create table entries( id integer primary key autoincrement, title string not null , text string nit null ); Flaskr |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |