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 request.method == '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

Flaskr

{% if not session.logged_in %} log in {% else %} log out {% endif %}
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %} {% block body %}{% endblock %}

{% extends "layout.html" %}
{% block body %}
  

Login

{% if error %}

Error: {{ error }}{% endif %}

Username:
Password:
{% endblock %}

{% extends "layout.html" %}
{% block body %}
  {% if session.logged_in %}
    
Title:
Text:
{% endif %}
    {% for entry in entries %}
  • {{ entry.title }}

    {{ entry.text|safe }} {% else %}
  • Unbelievable. No entries here so far {% endfor %}
{% endblock %}

试着运行吧? 肯定是不行滴,数据库弄了吗?

4、数据库sqllite

  • 安装

         请在官网下载

  python + flask + sqlite3做一个小博客_第1张图片

解压后,在环境变量中添加path

  • 创建数据库

flaskr文件夹中 打开cmd

$ sqlite3 flaskr.db

用命令.database 查询系统中的数据库,确认数据库已经成功创建

 

sqlite> .database

ok 大功搞成,启动程序试一下吧

 

你可能感兴趣的:(flask,python小项目,python)