在flas中创建查询字符串时出错

2024-09-27 00:15:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个烧瓶应用程序。你知道吗

这个应用程序允许用户上传图片,如果我在本地运行这个应用程序这个应用程序上传图片并保存到我指定的路径

现在我想为我的应用程序创建一个查询字符串,我将在其中创建URL并将其发送给人们以上载图像。你知道吗

但当我运行我的应用程序时,我收到了这个错误

werkzeug.routing.BuildError: Could not build url for endpoint 'index'. Did you forget to specify values ['property_id']?
Traceback (most recent call last)

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2309, in __call__

    return self.wsgi_app(environ, start_response)

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2295, in wsgi_app

    response = self.handle_exception(e)

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1741, in handle_exception

    reraise(exc_type, exc_value, tb)

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\_compat.py", line 35, in reraise

    raise value

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2292, in wsgi_app

    response = self.full_dispatch_request()

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request

    rv = self.handle_user_exception(e)

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1718, in handle_user_exception

    reraise(exc_type, exc_value, tb)

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\_compat.py", line 35, in reraise

    raise value

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request

    rv = self.dispatch_request()

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1799, in dispatch_request

    return self.view_functions[rule.endpoint](**req.view_args)

    File "C:\Users\prince.bhatia\Desktop\python-projects\new\app.py", line 77, in index

    return render_template('index.html', property_id= property_id)

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\templating.py", line 135, in render_template

    context, ctx.app)

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\templating.py", line 117, in _render

    rv = template.render(context)

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\jinja2\asyncsupport.py", line 76, in render

    return original_render(self, *args, **kwargs)

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\jinja2\environment.py", line 1008, in render

    return self.environment.handle_exception(exc_info, True)

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\jinja2\environment.py", line 780, in handle_exception

    reraise(exc_type, exc_value, tb)

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\jinja2\_compat.py", line 37, in reraise

    raise value.with_traceback(tb)

    File "C:\Users\prince.bhatia\Desktop\python-projects\new\templates\index.html", line 14, in top-level template code

    {{ dropzone.create(action_view='index') }}

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask_dropzone\__init__.py", line 330, in create

    action_url = url_for(action_view, **kwargs)

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\helpers.py", line 356, in url_for

    return appctx.app.handle_url_build_error(error, endpoint, values)

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2061, in handle_url_build_error

    reraise(exc_type, exc_value, tb)

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\_compat.py", line 35, in reraise

    raise value

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\helpers.py", line 345, in url_for

    force_external=external)

    File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\werkzeug\routing.py", line 1776, in build

    raise BuildError(endpoint, values, method, self)

    werkzeug.routing.BuildError: Could not build url for endpoint 'index'. Did you forget to specify values ['property_id']?

The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.

To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

    dump() shows all variables in the frame
    dump(obj) dumps all that's known about the object

下面是我的代码:

from flask import Flask, redirect, render_template, request, session, url_for, send_file
from flask_dropzone import Dropzone
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from flask_sqlalchemy import SQLAlchemy
import os
import psycopg2
import csv

app = Flask(__name__)
db = SQLAlchemy(app)
dropzone = Dropzone(app)
#app.config["SQLALCHEMY_DATABASE_URI"]="postgres://qpnwgdxnihlitm:22e4f6cbdb773f69aa468b2b7ddcd692552cb4102367ffc14c62f19403636477@ec2-54-243-223-245.compute-1.amazonaws.com:5432/d1ssufnnr78nll?sslmode=require"
app.config["SQLALCHEMY_DATABASE_URI"]= "postgresql://postgres:prince@25@localhost/images"
#app.config["SQLALCHEMY_DATABASE_URI"]='postgres://mapvmydehdyncf:7500963c956e3d5556df4a5f4fdd1a9a40f023c922bfe93194fb13b9322c86ad@ec2-23-21-165-188.compute-1.amazonaws.com:5432/d6lmau9918afdq?sslmode=require'
app.config['SECRET_KEY'] = 'supersecretkeygoeshere' 

# Dropzone settings
app.config['DROPZONE_UPLOAD_MULTIPLE'] = True
app.config['DROPZONE_ALLOWED_FILE_CUSTOM'] = True
app.config['DROPZONE_ALLOWED_FILE_TYPE'] = 'image/*'
app.config['DROPZONE_REDIRECT_VIEW'] = 'results'

# Uploads settings
app.config['UPLOADED_PHOTOS_DEST'] = '/uploads'

photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app)  # set maximum file size, default is 16MB


class Data(db.Model):
    __tablename__ = "image"
    id=db.Column(db.Integer, primary_key=True)
    link = db.Column(db.String(1000000), unique=True)

    def __init__(self, link):
        self.link = link

@app.route("/<string:property_id>", methods=['GET', 'POST'])
def index(property_id):

    # set session for image results
    if "file_urls" not in session:
        session['file_urls'] = []
    # list to hold our uploaded image urls
    file_urls = session['file_urls']

    # handle image upload from Dropszone
    if request.method == 'POST':
        file_obj = request.files
        for f in file_obj:
            file = request.files.get(f)

            # save the file with to our photos folder
            filename = photos.save(
                file,
                name=file.filename    
            )

            # append image urls

            file_urls.append(photos.url(filename))
            d = file_urls.append(photos.url(filename))

            for i in file_urls:
                data = Data(i)
                db.session.add(data)
                db.session.commit()


        session['file_urls'] = file_urls

        return "uploading..."
    # return dropzone template on GET request

    return render_template('index.html', property_id= property_id)


@app.route('/results')
def results():

    # redirect to home if no images to display
    if "file_urls" not in session or session['file_urls'] == []:
        return redirect(url_for('index'))

    # set the file_urls and remove the session variable
    file_urls = session['file_urls']
    session.pop('file_urls', None)
    dms = set(file_urls)
    get_length = len(dms)

    return render_template('results.html', dms=dms, get_length=get_length)

@app.route('/dashboard')
def dashboard():
    conn = psycopg2.connect("dbname='images' user='postgres' password='prince@25' host='localhost' port='5432' ")
    print(conn)
    cur = conn.cursor()
    data = cur.execute("SELECT DISTINCT link FROM image")
    m_dict = cur.fetchall()

    filename = "Productivity.csv"
    with open("./"+filename,'w', encoding="utf-8") as csvfile:
        csvfile = csv.writer(csvfile, m_dict)
        csvfile.writerow(["Link"])
        for i in range(0, len( m_dict )):
            csvfile.writerow( m_dict[i]  )

    news = cur.execute("DELETE FROM image")
    conn.commit()
    return send_file(filename, attachment_filename="Data.csv", as_attachment=True)

if __name__=="__main__":
    app.run(debug=True)

#app.run(debug=True)

这是我的索引.html你知道吗

<!DOCTYPE html>
<html>
    <head>
        <title>99Acres</title>
        {{ dropzone.load() }}
        {{ dropzone.style('border: 2px dashed #0087F7; margin: 10%; min-height: 400px;') }}
    </head>
    <body style="background-color:teal">
        <!--<h1 style="color:white;">99Acres</h1>-->
        <img align="right"src="https://img-d02.moneycontrol.co.in/news_image_files/2015/356x200/9/99acres_1902_356.jpg" width="80" height="80" alt="me">
        <h1 align="center" style="color:white">Welcome to 99acres image upload website</h1>
        <h3 align="center"style="color:white">Please Upload images in format[".JPG",".PNG",".JPEG"]</h3>
        <h3 align="center" style="color:white">**Please Note:Maximum Total image size is 5MB</h3> 
        {{ dropzone.create(action_view='index') }}
        <div class="list" align="center">
            <strong>Our Partners:</strong> <a href="http://www.naukri.com" class="">Naukri.com</a>-
            <a href="http://www.jeevansathi.com" class="" style="color:white">Jeevansathi Matrimonials</a>- <a href="http://www.icicicommunities.org" class="">ICICIcommunities.org </a><br>
            <br>
            <a href="../propadmin/" class=""style="color:white">Home </a>|| <a href="../property/about.php" class=""style="color:white">About Us </a>||
            <a href="/do/buyourservices/" class=""> Advertise with us </a>|| <a href="../property/terms.php" class=""style="color:white">Terms and Conditions</a> ||
            <a href="../property/contact.php" class=""style="color:white"> Contact us</a> ||<a href="../property/request_info.php" class=""style="color:white"> Reques1t info</a><br>
            <br>
            All rights reserved 2001 Info Edge India Ltd. 
        </div>
    </body>
</html>

这是我的结果.html你知道吗

<body style="background-color:teal">
<h1 align="center" style="color:white">Below Images Uploaded Successfully</h1>
<a href="{{ url_for('index') }}">Back</a><p>

<ul>
{% for file_url in dms %}
    <img style="height: 150px" src="{{ file_url }}">
{% endfor %}
</ul>
<h1 align="center" style="color:white">You can close this page or upload more image</h1>
<h1 align="center" style="color:white">Total number of images are : {{get_length}}</h1> <br><br><br><br>
<div class="list" align="center">
            <strong>Our Partners:</strong> <a href="http://www.naukri.com" class="">Naukri.com</a>-
            <a href="http://www.jeevansathi.com" class="" style="color:white">Jeevansathi Matrimonials</a>- <a href="http://www.icicicommunities.org" class="">ICICIcommunities.org </a><br>
            <br>
            <a href="../propadmin/" class=""style="color:white">Home </a>|| <a href="../property/about.php" class=""style="color:white">About Us </a>||
            <a href="/do/buyourservices/" class=""> Advertise with us </a>|| <a href="../property/terms.php" class=""style="color:white">Terms and Conditions</a> ||
            <a href="../property/contact.php" class=""style="color:white"> Contact us</a> ||<a href="../property/request_info.php" class=""style="color:white"> Reques1t info</a><br>
            <br>
            All rights reserved 2001 Info Edge India Ltd. 
        </div>
</body>

我读过以下帖子:

werkzeug.routing.BuildError: Could not build url for endpoint 'success'. Did you forget to specify values ['name']?

How do you get a query string on Flask?

werkzeug.routing.BuildError: Could not build url for endpointenter image description here


Tags: inpyappstylelocallineusersappdata
1条回答
网友
1楼 · 发布于 2024-09-27 00:15:37

render_template('index.html', property_id= property_id)

您的index.html不使用property_id。如果index.html确实不需要property_id参数,则可以放弃它

英寸索引.html,第14行

dropzone.create(action_view='index')

action_url = url_for(action_view, **kwargs)

后面的url_for会再次调用index()方法,但是错过了参数property_id,而且看起来您正在进行递归调用!你知道吗

相关问题 更多 >

    热门问题