Ejemplo n.º 1
0

class NameForm(Form):
    # StringField会被转换为input[type="field",label="What is your name?"]
    # 提交之前会执Require的validator
    name = StringField('What is your name?', validators=[Required()])
    submit = SubmitField('Submit')


'''
app.config常备用来存储一些配置信息,甚至还能够从文件中导入配置;
SECRET_KEY是常用来做加密的变量,它会被用来生成一个token,该token用于每次登陆时候的校验。
'''
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
bootstrap = Bootstrap(app)


@app.route('/', methods=['GET', 'POST'])
def index():
    name = None
    form = NameForm()
    if form.validate_on_submit():
        old_name = session.get('name')
        '''
        仅在名字发生了更新的时候调用flash()
        对于错误、确认、警告信息,Flask提供了flash()方法。
        使用分为python中调用flask()和在模板中呈现message两部分
        '''
        if old_name is not None and old_name != form.name.data:
            flash('Looks like you have changed your name!')
Ejemplo n.º 2
0
from flask import Flask
from flask.ext.login import LoginManager
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.mail import Mail
from config import config
from flask_oauthlib.client import OAuth

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy()
bootstrap = Bootstrap()
moment = Moment()
mail = Mail()

oauth = OAuth()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
Ejemplo n.º 3
0
from flask.ext.bootstrap import Bootstrap
from flask.ext.openid import OpenID
from flask.ext.sqlalchemy import SQLAlchemy
from raven.contrib.flask import Sentry
from raven.handlers.logging import SentryHandler
from raven.conf import setup_logging

app = Flask(__name__)

app.config.from_pyfile('../config.py')

if os.path.exists('config_local.py'):
    # Flask uses a different path than os.path.exist()
    app.config.from_pyfile('../config_local.py')

Bootstrap(app)
oid = OpenID(app)
db = SQLAlchemy(app)

if 'SENTRY_DSN' in app.config or 'SENTRY_DSN' in os.environ:
    sentry = Sentry(app)
    handler = SentryHandler(sentry.client)
    setup_logging(handler)

# Let's begin the circular imports!
import talkatv.filters

import talkatv.views
import talkatv.profile.views
import talkatv.api.views
import talkatv.comment.views
Ejemplo n.º 4
0
    'SECRET_KEY'] = 'hard to guess string'  # app.config作为字典存储框架、扩展和程序本身的配置变量,标准字典形式
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(
    basedir, 'data.sqlite')  # 指定数据库URI
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = 587  # 465
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin <' + app.config[
    'MAIL_USERNAME'] + '>'
app.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN')

manager = Manager(app)  # 命令行解析功能
bootstrap = Bootstrap(app)  # 集成Bootstrap框架
moment = Moment(app)  # 渲染日期和时间
db = SQLAlchemy(app)  # 创建数据库
mail = Mail(app)  # 初始化Flask-Mail

migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)


class NameForm(Form):
    name = StringField('What is your name?', validators=[Required()])
    submit = SubmitField('Submit')


class Role(db.Model):
    __tablename__ = 'roles'
Ejemplo n.º 5
0
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True  #设置这一项是每次请求结束后都会自动提交数据库中的变动

#################################user 相关
app.config['SECRET_KEY'] = 'f**k money'  # 必须 用于加密

login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)

##################################下面都是处理数据库的##############################################################################
##################################下面都是处理数据库的##############################################################################

db = SQLAlchemy(app)  #实例化

bootstrap = Bootstrap(
    app
)  #https://www.jianshu.com/p/102afa96bc4b bootstrap的使用   {% extends "bootstrap/base.html" %}会自动引用,不需要copy过来这个模板


class Tupian(db.Model):  #这里的类名和下面的tablename随便取
    __tablename__ = 'tupian'
    id = db.Column(db.Integer,
                   nullable=False,
                   primary_key=True,
                   autoincrement=True)
    name = db.Column(db.String(255),
                     nullable=False,
                     unique=True,
                     server_default='',
                     index=True)
    label = db.Column(db.String(255), nullable=False, server_default='')
Ejemplo n.º 6
0
            self._validate_schema(dynamic_schema, field, dct)
        else:
            self._error(
                field, "Could not find any %s for query %s" %
                (schema['resource'], query))

    def _validate_keyschema(self, schema, field, dct):
        "Validate all keys of dictionary `dct` against schema `schema`."
        for key, value in dct.items():
            self._validate_schema(schema, key, value)


settingsfile = path.join(path.abspath(path.dirname(__file__)), 'settings.py')
api = Eve(API_NAME, validator=KeySchemaValidator, settings=settingsfile)

Bootstrap(api)
api.register_blueprint(eve_docs, url_prefix='/docs')

resource_url = lambda resource: '/' + api.config['URL_PREFIX'] + '/' + resource


def get_schema(resource):
    "Get the schema for a given resource."
    return api.config['DOMAIN'][resource]['schema']


def add_document(resource, document):
    "Add a new document to the given resource."
    with api.test_request_context(resource_url(resource)):
        return post(resource, payl=document)
Ejemplo n.º 7
0
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.pymongo import PyMongo
from flask.ext.login import LoginManager

app = Flask(__name__)

#Configuration of application, see configuration.py, choose one and uncomment.
#app.config.from_object('configuration.ProductionConfig')
app.config.from_object('app.configuration.DevelopmentConfig')
#app.config.from_object('configuration.TestingConfig')

bs = Bootstrap(app)  #flask-bootstrap
db = SQLAlchemy(app)  #flask-sqlalchemy

lm = LoginManager()
lm.setup_app(app)
lm.login_view = 'login'

from app import views, models
Ejemplo n.º 8
0
def make_app(env="dev"):
    """
    This is still needlessly complicated.

    Returns a Flask WSGI instance.
    """
    debug = env == "dev"

    url_root = dict(
        dev="/",
        build="/dist/",
        test="/dist/",
        prod="/"
    )[env]

    app_home = os.path.dirname(__file__)

    cfg = dict(
        dev=dict(
            static_url_path="/static",
            template_folder="./templates",
            static_folder=opa(opj(app_home, "static"))
        ),
        build=dict(
            static_url_path="/",
            template_folder="./templates",
            static_folder=opa(opj(app_home, "static"))
        ),
        test=dict(
            static_url_path="/dist",
            template_folder="../dist",
            static_folder=opa(opj(app_home, "..", "dist"))
        ),
        prod=dict(
            static_url_path="/static",
            template_folder="./templates",
            static_folder=opa(opj(app_home, "static"))
        )
    )[env]

    app = Flask(__name__, **cfg)

    app.config.update(dict(
        CSRF_ENABLED=debug,
        SECRET_KEY=os.environ.get("FLASK_SECRET_KEY", "totally-insecure"),
        DEBUG=debug,
        ASSETS_DEBUG=debug,
        BOOTSTRAP_JQUERY_VERSION=None
    ))

    Bootstrap(app)

    def font_stuff(url):
        """
        Some font URL rewriting
        """
        repl = "./lib/awesome/font/"
        if env == "build":
            repl = "./font/"
        return url.replace("../font/", repl)

    fix_font_css = CSSRewrite(replace=font_stuff)

    assets = Environment(app)

    bundles = YAMLLoader(os.path.join(app_home, 'assets.yaml')).load_bundles()

    for to_fix in ["prod", "build"]:
        bundles["css-%s" % to_fix].filters.insert(0, fix_font_css)

    for name, bundle in bundles.iteritems():
        assets.register(name, bundle)


    @app.route(url_root)
    def index():
        kwargs = {
            "gh_client_id": os.environ.get("GITHUB_CLIENT_ID", 
                "deadbeef")
        }

        return render_template("index.html", env=env, **kwargs)


    @app.route("/login")
    def login(code=None):
        return render_template("login.html")


    @app.route("/oauth")
    def oauth():
        oauth_args = dict(
            code=request.args.get("code", ""),
            state=request.args.get("state", ""),
            client_id=os.environ["GITHUB_CLIENT_ID"],
            client_secret=os.environ["GITHUB_CLIENT_SECRET"]
        )
        
        req = requests.post(
            "https://github.com/login/oauth/access_token",
            data=oauth_args
        )
        
        query = urlparse.parse_qs(req.content)
        
        return query["access_token"][0]

    return app
Ejemplo n.º 9
0
#!/usr/bin/python
# -*- coding:utf-8 -*-
################################################################
# 服务器程序
################################################################
import json
import time
import sys
from flask import Flask, abort, render_template, redirect, send_from_directory, request, make_response
from flask.ext.bootstrap import Bootstrap
sys.path.append('..')
from tools.conf.website_conf import website_list, website_link
from tools.general_tools import get_top_n_website_scores

server = Flask(__name__)
bootstrap = Bootstrap(server)


def generate_result(scores):
    result_list = []
    for score in scores:
        result = {}
        result['website'] = score[0]
        result['score'] = '%.3f' % (score[1] * 100)
        result['link'] = website_link[score[0]][0]
        result['type'] = website_link[score[0]][1]
        result_list.append(result)
    return result_list  # sorted(result_list, key=lambda x: x['score'], reverse=True)


@server.route('/')
Ejemplo n.º 10
0
def create_app(test_config=None):                   # For automated tests
    # Setup Flask and read config from ConfigClass defined above
    app = Flask(__name__)
    app.config.from_object(__name__ + '.ConfigClass')

    # Load local_settings.py if file exists         # For automated tests
    try:
        app.config.from_object('local_settings')
    except:
        pass

    # Over-write app config                         # For automated tests
    if test_config:
        for key, value in test_config.items():
            app.config[key] = value

    # Setup Flask-Mail, Flask-Babel and Flask-SQLAlchemy
    app.mail = Mail(app)
    app.babel = babel = Babel(app)
    app.db = db = SQLAlchemy(app)

    @babel.localeselector
    def get_locale():
        translations = [str(translation)
                        for translation in babel.list_translations()]
        return request.accept_languages.best_match(translations)

    # Define User model. Make sure to add flask.ext.user UserMixin!!
    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        active = db.Column(db.Boolean(), nullable=False, default=False)
        email = db.Column(db.String(255), nullable=False, unique=True)
        password = db.Column(db.String(255), nullable=False, default='')
        username = db.Column(db.String(50), nullable=False, unique=True)
        confirmed_at = db.Column(db.DateTime())
        reset_password_token = db.Column(
            db.String(100), nullable=False, default='')
        tweets = db.relationship('Tweet', backref='user', lazy='dynamic')

    app.User = User

    class Tweet(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        text = db.Column(db.String(144), nullable=False, default='')
        tweeted_at = db.Column(db.DateTime())
        user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    # Create all database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db,  User)       # Select database adapter
    # Init Flask-User and bind to app
    user_manager = UserManager(db_adapter, app)

    # Setup forms
    class TweetForm(Form):
        text = StringField('Message', validators=[Required()])
        submit = SubmitField('Submit')

    # The '/' page is accessible to anyone
    @app.route('/')
    def home_page():
        if current_user.is_authenticated():
            return profile_page()
        return render_template("index.html")

    # The '/profile' page requires a logged-in user
    @app.route('/profile')
    # Use of @login_required decorator
    @login_required
    def profile_page():
        return render_template("profile.html")

    @app.route('/tweet/new', methods=['GET', 'POST'])
    @login_required
    def new_tweet():
        form = TweetForm()
        if form.validate_on_submit():
            tweet = Tweet()
            form.populate_obj(tweet)
            tweet.tweeted_at = datetime.now()
            tweet.user = current_user
            db.session.add(tweet)
            db.session.commit()
            flash("Your message is tweeted.")
            return redirect(url_for("list_tweet"))
        return render_template("new_tweet.html", form=form)

    @app.route('/tweet/list')
    @login_required
    def list_tweet():
        tweets = Tweet.query.order_by(Tweet.tweeted_at).limit(50)
        print(tweets[0].user.username)
        return render_template("list_tweet.html", tweets=tweets)

    bootstrap = Bootstrap(app)
    return app
Ejemplo n.º 11
0
    'name': 'data/database.db',
    'engine': 'peewee.SqliteDatabase',
}
DEBUG = True
SECRET_KEY = 'ssshhhh'
CSRF_ENABLED = False
APP_DIR = 'app'
BOOTSTRAP_JQUERY_VERSION = None
SOURCES = []
DESTINATIONS = []
""" Load Basic config """
webackup = Flask('modules',
                 static_folder="static",
                 template_folder='templates')
webackup.config.from_object(__name__)
Bootstrap(webackup)

# instantiate the db wrapper
db = Database(webackup)

# instatiate the login
login_manager = LoginManager()
login_manager.setup_app(webackup)

# initiate scheduler
sched = Scheduler()
sched.add_jobstore(ShelveJobStore('data/scheduler.db'), 'default')
sched.start()
""" Registering the blueprint controller """
dirs = os.listdir(APP_DIR)
for module in dirs: