Commits

Anonymous committed d9834d9

add an flask-sqlalchemy example

Comments (0)

Files changed (10)

examples/example/example/__init__.py

+# -*- encoding:utf-8 -*-
+from flask import Flask
+from example.views.frontend import frontend
+from .models import db
+
+def create_app(config=None):
+    app = Flask(__name__)
+    if config:
+        app.config.from_object(config)
+    db.init_app(app)
+    app.register_module(frontend)
+    return app

examples/example/example/models.py

+#!/usr/bin/env python
+from flaskext.sqlalchemy import SQLAlchemy
+from werkzeug import generate_password_hash, check_password_hash
+
+db = SQLAlchemy()
+
+class User(db.Model):
+    __tablename__ = 'users'
+    id = db.Column(db.Integer, primary_key=True)
+    username = db.Column(db.String(80), unique=True)
+    pw_hash = db.Column(db.String(80))
+
+    def __init__(self, username, password):
+        self.username = username
+        self.set_password(password)
+
+    def set_password(self, password):
+        self.pw_hash = generate_password_hash(password)
+
+    def check_password(self, password):
+        return check_password_hash(self.pw_hash, password)
+
+    def __repr__(self):
+        return '<User %r>' % self.username
+

examples/example/example/static/style.css

+body            { font-family: sans-serif; background: #eee; }
+a, h1, h2       { color: #377BA8; }
+h1, h2          { font-family: 'Georgia', serif; margin: 0; }
+h1              { border-bottom: 2px solid #eee; }
+h2              { font-size: 1.2em; }
+
+.page           { margin: 2em auto; width: 35em; border: 5px solid #ccc;
+                  padding: 0.8em; background: white; }
+.entries        { list-style: none; margin: 0; padding: 0; }
+.entries li     { margin: 0.8em 1.2em; }
+.entries li h2  { margin-left: -1em; }
+.add-entry      { font-size: 0.9em; border-bottom: 1px solid #ccc; }
+.add-entry dl   { font-weight: bold; }
+.metanav        { text-align: right; font-size: 0.8em; padding: 0.3em;
+                  margin-bottom: 1em; background: #fafafa; }
+.flash          { background: #CEE5F5; padding: 0.5em;
+                  border: 1px solid #AACBE2; }
+.error          { background: #F0D6D6; padding: 0.5em; }

examples/example/example/templates/index.html

+{% extends "layout.html" %}
+{% block body %}
+  {% if session.logged_in %}
+   Welcome, {{ session.username }} !
+  {% else %}
+  Please <a href="{{ url_for("login")}}">log in </a>!
+  {% endif %}
+{% endblock %}

examples/example/example/templates/layout.html

+<!doctype html>
+<title>Flaskr</title>
+<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
+<div class=page>
+  <h1>Flask-SQLAlchemy test</h1>
+  <div class=metanav>
+  {% if not session.logged_in %}
+    <a href="{{ url_for('login') }}">log in</a>
+  {% else %}
+    <a href="{{ url_for('logout') }}">log out</a>
+  {% endif %}
+  </div>
+  {% for message in get_flashed_messages() %}
+    <div class=flash>{{ message }}</div>
+  {% endfor %}
+  {% block body %}{% endblock %}
+</div>

examples/example/example/templates/login.html

+{% extends "layout.html" %}
+{% block body %}
+  <h2>Login</h2>
+  {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}
+  <form action="{{ url_for('login') }}" method=post>
+    <dl>
+      <dt>Username:
+      <dd><input type=text name=username>
+      <dt>Password:
+      <dd><input type=password name=password>
+      <dd><input type=submit value=Login>
+    </dl>
+  </form>
+{% endblock %}

examples/example/example/views/__init__.py

+# -*- encoding:utf-8 -*-
+
+
+
+
+

examples/example/example/views/frontend.py

+# -*- encoding:utf-8 -*-
+from flask import Module
+from flask import Flask, request, session, g, redirect, url_for, abort, \
+             render_template, flash
+
+from example.models import User
+
+frontend = Module(__name__)
+
+@frontend.route('/')
+def index():
+    return render_template('index.html')
+
+@frontend.route('/login', methods=['GET', 'POST'])
+def login():
+    error = None
+    if request.method == 'POST':
+        username = request.form['username']
+        password = request.form['password']
+        user = User.query.filter_by(username=username).first()
+        if not user or not user.check_password(password):
+            error = 'Invalid username or  password'
+        else:
+            session['logged_in'] = True
+            session['username'] = username
+            flash('You were logged in')
+            return redirect(url_for('index'))
+    return render_template('login.html', error=error)
+
+
+@frontend.route('/logout')
+def logout():
+    session.pop('logged_in', None)
+    flash('You were logged out')
+    return redirect(url_for('index'))

examples/example/manage.py

+#!/usr/bin/env python2
+# -*- encoding:utf-8 -*-
+
+from flask import Flask
+from flaskext.actions import Manager
+import settings
+from example import create_app,db
+
+app = create_app(settings)
+manager = Manager(app)
+
+@manager.register('init_db')
+def init_db(app):
+    def action():
+        """
+        init database
+        """
+        ctx = app.test_request_context()
+        ctx.push()
+        db.create_all()
+        ctx.pop()
+    return action
+
+@manager.register('create_user')
+def create_user(app):
+    def action(username=('u','testuser'),password=('p','123456')):
+        """
+        create user
+        """
+        from example.models import User
+        ctx = app.test_request_context()
+        ctx.push()
+        user = User(username,password)
+        db.session.add(user)
+        db.session.commit()
+        ctx.pop()
+    return action
+
+
+if __name__ == "__main__":
+    manager.run()
+

examples/example/settings.py

+# -*- encoding:utf-8 -*-
+
+# SQL Alchemy settings
+SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db'
+
+SECRET_KEY = '?NA6tv$dJ)_%}ia<"3+1,U3&jmAt{R^O'
+
+DEBUG = True
+