使用 Python 上传功能

Upload Function with Python

我一直在尝试使用 jqxUploadFiles 但我需要使用 python.

而不是 php

在如下代码中;

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()" 这样的函数,但我不明白 "create_app()" 和 Blueprint() 创建的 "app" 如何相互关联以及我该如何使用它在 upload_file().

首先,你最好制作一个文件定义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>

有什么问题请尽管问!