Beispiel #1
0
 def add_route(self, action_name, path='', reset_namespace=False, on_member=False, **options):
     if reset_namespace:
         rule = path
     else:
         if on_member:
             rule = '{0}/<int:{1}_id>{2}/'.format(self.resource_path, self.resource_name, path)
         else:
             rule = '{0}{1}/'.format(self.resource_path, path)
     app.route(rule, **options)(getattr(self, action_name))
Beispiel #2
0
 def decorator(f):
     # This sets up routes for both the subdomain and the url path prefix.
     # The order of these determines which one will be used by url_for -
     # in this case it's the prefix route.
     # We may want to have a configuration option to specify whether to
     # use a subdomain or a url path prefix.
     prefix_route = app.route("/<library_short_name>" + path, *args, **kwargs)(f)
     subdomain_route = app.route(path, subdomain="<library_short_name>", *args, **kwargs)(prefix_route)
     default_library_route = app.route(path, *args, **kwargs)(subdomain_route)
     return default_library_route
Beispiel #3
0
def login():
    return render_template("login.html"

@app.route('/register')
def register():
    return render_template("register.html"

@app.route('/profile')
def profile():
    return render_template("profile.html"
Beispiel #4
0
 def decorator(f):
     # This sets up routes for both the subdomain and the url path prefix.
     # The order of these determines which one will be used by url_for -
     # in this case it's the prefix route.
     # We may want to have a configuration option to specify whether to
     # use a subdomain or a url path prefix.
     prefix_route = app.route("/<library_short_name>" + path, *args, **kwargs)(f)
     subdomain_route = app.route(path, subdomain="<library_short_name>", *args, **kwargs)(prefix_route)
     default_library_route = app.route(path, *args, **kwargs)(subdomain_route)
     return default_library_route
Beispiel #5
0
	def decorator(fn):
		@functools.wraps(fn)
		def wrapper(*args, **kwargs):
			ret = fn(*args, **kwargs)
			obj = {"status": "success"}
			if ret:
				obj.update(ret)
			return jsonify(obj)
		return app.route("/ajax/" + action, methods=["POST"])(wrapper)
Beispiel #6
0
def load_user(id):
    return UserProfile.query.get(int(id))

###
# The functions below should be applicable to all Flask apps.
###



@app.route('/<file_name>.txt')
Beispiel #7
0
	def decorator(fn):
		@functools.wraps(fn)
		def wrapper(*args, **kwargs):
			if requires_login and not auth.get_logged_in_user():
				return jsonify({"error": "login_required", "status": "error"})
			ret = fn(*args, **kwargs)
			obj = {"status": "success"}
			if ret:
				obj.update(ret)
			return jsonify(obj)
		return app.route("/ajax/" + action, methods=["POST"])(wrapper)
Beispiel #8
0
    def decorator(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            if requires_login and not auth.get_logged_in_user():
                return jsonify({"error": "login_required", "status": "error"})
            ret = fn(*args, **kwargs)
            obj = {"status": "success"}
            if ret:
                obj.update(ret)
            return jsonify(obj)

        return app.route("/ajax/" + action, methods=["POST"])(wrapper)
Beispiel #9
0
    def decorator(f):
        # By default, creating a route with a slash will make flask redirect
        # requests without the slash, even if that route also exists.
        # Setting strict_slashes to False disables this behavior.
        # This is important for CORS because the redirects are not processed
        # by the CORS decorator and won't be valid CORS responses.

        # Decorate f with four routes, with and without the slash, with a prefix or subdomain
        prefix_slash = app.route("/<library_short_name>" + path_without_slash +
                                 "/",
                                 strict_slashes=False,
                                 *args,
                                 **kwargs)(f)
        prefix_no_slash = app.route(
            "/<library_short_name>" + path_without_slash, *args,
            **kwargs)(prefix_slash)
        subdomain_slash = app.route(path_without_slash + "/",
                                    strict_slashes=False,
                                    subdomain="<library_short_name>",
                                    *args,
                                    **kwargs)(prefix_no_slash)
        subdomain_no_slash = app.route(path_without_slash,
                                       subdomain="<library_short_name>",
                                       *args,
                                       **kwargs)(subdomain_slash)
        default_library_slash = app.route(path_without_slash, *args,
                                          **kwargs)(subdomain_no_slash)
        default_library_no_slash = app.route(path_without_slash + "/", *args,
                                             **kwargs)(default_library_slash)
        return default_library_no_slash
Beispiel #10
0
def todo_list(*args, **kwargs):
    user = kwargs.get('user')
    task_list = Task.query.filter_by(user_id=user.id).all()
    return render_template('todo/list.html', data_list=task_list, title="Ta Do List | TodoApp"
    

@app.route('/todos/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def todo_edit(*args, **kwargs):
    user = kwargs.get('user')
    id = kwargs.get('id')
    current_task = Task.query.get_or_404(id)
    form = TaskForm(
        content=current_task.content,
        status=current_task.status
    )
    if form.validate_on_submit():
        current_task.content = form.content.data
        current_task.status = form.status.data
        db.session.add(current_task)
        db.session.commit()
        flash('Your Task has been updated!')
        return redirect(url_for('todo_list'))
    return render_template('todo/add.html', form=form, title='Edit Task | TodoApp')


@app.route('/todos/delete/<int:id>', methods=['GET','POST'])
def todo_delete(*args, **kwargs):
    id = kwargs.get('id')
    current_task = Task.query.get_or_404(id)
    form = DeleteForm()
    if form.validate_on_submit():
        db.session.delete(current_task)
        db.session.commit()
        flash('Your Task has been deleted!')
        return redirect(url_for('todo_list'))
    return render_template('todo/del.html', form=form, title='Delete Task | TodoApp')
Beispiel #11
0
    def decorator(f):
        # By default, creating a route with a slash will make flask redirect
        # requests without the slash, even if that route also exists.
        # Setting strict_slashes to False disables this behavior.
        # This is important for CORS because the redirects are not processed
        # by the CORS decorator and won't be valid CORS responses.

        # Decorate f with four routes, with and without the slash, with a prefix or subdomain
        prefix_slash = app.route("/<library_short_name>" + path_without_slash + "/", strict_slashes=False, *args, **kwargs)(f)
        prefix_no_slash = app.route("/<library_short_name>" + path_without_slash, *args, **kwargs)(prefix_slash)
        subdomain_slash = app.route(path_without_slash + "/", strict_slashes=False, subdomain="<library_short_name>", *args, **kwargs)(prefix_no_slash)
        subdomain_no_slash = app.route(path_without_slash, subdomain="<library_short_name>", *args, **kwargs)(subdomain_slash)
        default_library_slash = app.route(path_without_slash, *args, **kwargs)(subdomain_no_slash)
        default_library_no_slash = app.route(path_without_slash + "/", *args, **kwargs)(default_library_slash)
        return default_library_no_slash
Beispiel #12
0
import os
from flask import Flask, render_template, send_from_directory
from flask.ext.sqlalchemy import SQLAlchemy
from flask_socketio import SocketIO, emit

from app import app, db
import uploads
from helpers.errorhandler import InvalidUsage
from remote import socketio
from widget import create, get_all, get, init, deleteall

from flask import request, json

app.route("")


def index():
    return send_from_directory(app.config['STATIC_FOLDER'], 'index.html')


@app.route("/")
def index():
    return send_from_directory(app.config['STATIC_FOLDER'], 'index.html')


@app.route("/builder")
def builder():
    return send_from_directory(app.config['STATIC_FOLDER'], 'builder.html')


@app.route("/display")
Beispiel #13
0
from app import app,render_template, redirect, url_for, request

@app.route('/')
@app.route('/index')
def index():
    return "Hello, World!"
app.route('/login',methods=['GET','POST'])
def login():
    error=none
    if request=='POST':
        if request.form['username'] !='admin' or request.form['password'] !='admin':
            error= 'Please enter correct name or password'
            else:
                return redirect(url_for('home'))
    return render_template ('login.html', error=error)
 
    return render_template('register.html', form=form)


@app.route("/api/cars", methods=["GET", "POST"])
def cars():

    render_template("cars.html")
    render_template("addcars.html")


@app.route("/api/cars/{car_id}", methods=["GET"])
def car_details(id):
    render_template("car_details.html")


app.route("/api/cars/{car_id}/favourites")


def add_favourites(id):
    render_template("favourites.html")


app.route("/api/search")


def search():
    render_template("search.html")


app.route("/api/user/{user_id")
Beispiel #15
0
def create_model_func(model, Form, form_func=None):
    # 模板-添加记录
    def add():
        if form_func != None:
            form = form_func(Form)
        else:
            form = Form()
        if form.validate_on_submit():
            kw = {}
            for each in form:
                if each.id != 'csrf_token':
                    key = each.name
                    value = each.data
                    if value != '':
                        if isinstance(each, BooleanSelectField):
                            if value == '0':
                                value = False
                            if value == '1':
                                value = True
                        # 搜索名字对应ID再插入
                        elif isinstance(each, NeedSearchIdField):
                            rl_model = getattr(models, each.related_model)
                            related_model = rl_model.query.filter_by(
                                **{
                                    each.related_column: value
                                }).first()
                            if related_model is None:
                                flash('添加失败, 未找到(%s)' % each.data)
                                return form.redirect()
                            else:
                                value = related_model.id
                        kw.update({key: value})
            try:
                # 一次插入最多不超过4条
                add_count = int(request.form.get('add_count', 1))

                assert add_count > 0 and add_count < 5

                for i in range(add_count):
                    obj = model(**kw)
                    db.session.add(obj)

                db.session.commit()

            except Exception as e:
                print(e)
                flash('添加失败')
        else:
            flash('表单填写无效')
            for each in form:
                for error in each.errors:
                    print('[Warnning] Form submit failed: %s - %s' %
                          (each.name, error))
        return form.redirect()

    add.__name__ = model.__name__ + '_add'
    # 装饰 @login_required
    add = login_required(add)
    app.route('/%s/add/' % model.__name__, methods=['GET', 'POST'])(add)

    # 模板-删除记录
    def delete(ID):
        form = Form()
        obj = model.query.get(ID)
        try:
            db.session.delete(obj)
            db.session.commit()
        except:
            flash('删除失败')
        return form.redirect()

    delete.__name__ = model.__name__ + '_delete'
    # 装饰 @login_required
    delete = login_required(delete)
    app.route('/%s/<int:ID>/delete/' % model.__name__,
              methods=['GET', 'POST'])(delete)

    # 模板-修改记录
    def update(ID):
        if form_func != None:
            form = form_func(Form)
        else:
            form = Form()
        # 检查被更新记录是否存在
        obj = model.query.get(ID)
        if obj is not None:
            if form.validate_on_submit():
                for each in form:
                    if each.id != 'csrf_token':
                        key = each.name
                        value = each.data
                        if key != 'id':
                            if value == '':
                                value = None
                            elif isinstance(each, BooleanSelectField):
                                if value == '0':
                                    value = False
                                if value == '1':
                                    value = True
                            elif isinstance(each, NeedSearchIdField):
                                rl_model = getattr(models, each.related_model)
                                related_model = rl_model.query.filter_by(
                                    **{
                                        each.related_column: value
                                    }).first()
                                if related_model is None:
                                    flash('修改失败')
                                    return form.redirect()
                                else:
                                    value = related_model.id
                            setattr(obj, key, value)
                try:
                    db.session.commit()
                except:
                    db.session.rollback()
                    flash('更新失败')
            else:
                # 后台打印表单无效的原因
                flash('表单填写无效')
                for each in form:
                    for error in each.errors:
                        print('[Warnning] Form submit failed: %s - %s' %
                              (each.name, error))
        else:
            flash('更新失败: 未找到 ID:%d 对映的记录' % ID)
        return form.redirect()

    update.__name__ = model.__name__ + 'update'
    # 装饰 @login_required
    update = login_required(update)
    app.route('/%s/<int:ID>/update/' % model.__name__,
              methods=['GET', 'POST'])(update)
Beispiel #16
0
def index():
        return render_template("index.html")
<<<<<<< HEAD
@app.route('/settings',methods=['POST','GET'])
@app.route('/settings/profile',methods=['POST','GET'])
def profile():
        error = None
<<<<<<< HEAD
        cookie = request.cookies.get('username')
        if (cookie == resp.
=======
        #cookie = request.cookies.get('username')
        #if (cookie == resp.
>>>>>>> d13fdbf11e018e7c6e6afdf21ddcb3772b73dbb0
=======
@app.route('/welcome',methods=['POST','GET'])
def welcome():
>>>>>>> 803f2e15234c4c893ec63498a6a5d8f283b2db25
        if request.method == 'POST':
                resp = make_response(render_template('index.html'))
                resp.set_cookie('username',request.form['username'])
                resp.set_cookie('nickname',request.form['nickname'])
                miss = models.User.query.filter_by(username=request.form['username']).first()
                if miss == None:
                        m = hashlib.md5()
                        m.update(request.form['password'])
                        psw = m.hexdigest()
                        psw = request.form['password']
                        user = models.User(username=request.form['username'] , nickname=request.form['nickname'] ,email='null',password=psw)
                        db.session.add(user)
                        db.session.commit()
Beispiel #17
0
def account():
        return render_template("account.html")
@app.route('/settings/following')
Beispiel #18
0
def following():
        return render_template("following.html")
@app.route('/update',methods=['POST','GET'])
Beispiel #19
0
        return redirect(url_for('edit_profile'))
    elif request.method == 'GET':
        form.username.data = current_user.username
        form.about_me.data = current_user.about_me
    return render_template('edit_profile.html', title=_('Edit Profile'),
                           form=form)


@app.route("/")
def index():
   return render_template("upload.html")

APP_ROOT = os.path.dirname(os.path.abspath(__file__)


@app.route("/upload", methods=['POST'])
def upload():
 target = os.path.join(APP_ROOT, 'images/')
priint(target)

if not os.path.isdir(target):
os.mkdir(target)

for file in request.files.getlist("file"):
print(file)
filename = file.filename
destination = "/".join([target, filename])
print(destination)
file.save(destination)
return render_template("complete.html")
Beispiel #20
0
    return  render_template('create_profile.html',error='error')






@app.route('/profiles',methods=["GET"])
def profiles():
   return render_template('view_profile.html')







app.route('profile/<userid>',methods=["POST"])
def profile():
    return render_template('view_profile_list')








if __name__ == '__main__':
    app.run(debug=True,host="0.0.0.0",port="8888")
Beispiel #21
0
from app import app
from db import close_db_connection, init_db
from controllers import login, logout, add_entry, show_entries

app.config.from_object('settings')

app.route('/')(show_entries)
app.route('/add', methods=['POST'])(add_entry)
app.route('/login', methods=['GET', 'POST'])(login)
app.route('/logout')(logout)


if __name__ == '__main__':
    app.teardown_appcontext(close_db_connection)
    init_db(app)
    app.run()