使用Python

时间:2017-07-29 10:21:06

标签: python flask flask-sqlalchemy jqwidget

我一直在尝试使用jqxUploadFiles而不是php,我需要使用python。

在下面的代码中;

from flask import request
from flask.ext.uploads import UploadSet, configure_uploads, ALL

def upload_file():

    files = UploadSet('files', ALL)
    app.config['UPLOADED_FILES_DEST'] = '/uploads'
    configure_uploads(app, files)
    filename = files.save(request.files['files'])
    return filename

其中app = Flask(__name__)

但在这个项目中有;

main = Blueprint('main', __name__)

使用的地方如@main.route('/', methods=['GET', 'POST'])

并且有一个create_app函数;

def create_app():
    app = Flask(__name__)
    app.config.from_object(config['development'])

    with app.app_context():
        db.app = app
        db.init_app(app)
        db.create_all()

并在manage.py文件中使用;

app = create_app()
manager = Manager(app)


def make_shell_context():
    return dict(app=app, db=db)
manager.add_command("shell", Shell(make_context=make_shell_context))


@manager.command
def test():
    """Run the unit tests."""
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)


if __name__ == '__main__':
    manager.run()

所以我需要使用像" upload_file()"这样的函数。但我无法理解" app"由" create_app()"创建和Blueprint()相互关联,如何在upload_file()中使用它。

1 个答案:

答案 0 :(得分:0)

首先,您最好定义一个文件app,并从其他脚本文件中使用它。

使用此app,您可以注册Blueprint对象。

以下示例实际上是一个有效的脚本。

app.py

from flask import Flask

app = Flask(__name__)

main.py

from flask import Blueprint
from flask_script import Server, Manager, Shell
from view import top
from app import app

app.register_blueprint(top.main)

if __name__ == '__main__':
    app.run(host='192.168.33.40') # please change host

view/top.py

from flask import Blueprint
main = Blueprint("top", __name__, url_prefix="/")

from flask import request, render_template, redirect
from flask.ext.uploads import UploadSet, configure_uploads, ALL

from app import app

def upload_file():

    files = UploadSet('files', ALL)
    app.config['UPLOADED_FILES_DEST'] = '/tmp' # please change
    configure_uploads(app, files)
    filename = files.save(request.files['files'])
    return filename

@main.route('/', methods=['GET'])
def index():
    return render_template('top/index.html')

@main.route('upload', methods=['GET', 'POST'])
def upload():
    upload_file()
    return redirect('/')

templates/top/index.html

<form method=POST enctype=multipart/form-data action="/upload">
    <input type=file name=files>
    <input type=submit value=upload>
</form>

如果您有任何疑问,请提出任何问题!