简体   繁体   中英

Get value from URL in another app.route

I have a Flask application that shows text under the URL http://<webroot>/idea/<idea_id> , eg http://localhost/idea/123 . The idea_id is requested from a database

@app.route("/idea/<idea_id>", methods=["POST","GET"])
def get_idea(idea_id):
    db = get_db()
    cur = db.execute("select id, title, description, image from ideas where id=?", (idea_id,))
    ideas = cur.fetchall()
    args = request.path
    return render_template("idea.html", ideas=ideas)

In that page I got a file upload:

<form action="{{ url_for("upload_image") }}" method="post" enctype="multipart/form-data">
    <p><input type="file" name="image">
    <input type=submit value="Hochladen">
</form>

Here's the code that does the upload:

@app.route("/upload_image", methods=["POST", "GET"])
def upload_image():
    if not session.get("logged_in"):
        abort(401)
    image = request.files["image"]
    if image and allowed_file(image.filename):
        db = get_db()
        idea_id = request.view_args["idea_id"]
        filename = secure_filename(image.filename)
        db.execute("INSERT OR REPLACE INTO ideas (id, image) VALUES (?, ?)", (idea_id, filename))
        image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return flash("Bild hochgeladen!")
    return redirect(url_for("index"))

I want to insert the path of the image into the database and link it to the ID of the idea (idea_id).

My question is how to get the idea_id-value from used in the URL? I guess I need to URL processors, but I can't wrap my head around the whole process yet.

I would do it as a hidden input in your form.

<form action="{{ url_for("upload_image") }}" method="post" enctype="multipart/form-data">
    <input type="hidden" name="idea_id" value="{{ idea_id }}">
    <p><input type="file" name="image">
    <input type=submit value="Hochladen">
</form>

This would also require modifying your view.

@app.route("/idea/<idea_id>", methods=["POST","GET"])
def get_idea(idea_id):
    db = get_db()
    cur = db.execute("select id, title, description, image from ideas where id=?", (idea_id,))
    ideas = cur.fetchall()
    args = request.path
    return render_template("idea.html", ideas=ideas, idea_id=idea_id)

This would put idea_id into request.form . You can then access it from upload_image with request.form['idea_id'] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM