python - 为什么我的表单试图提交到错误的端点?

标签 python html mongodb dictionary flask

我有一个 python 脚本和一个 mongoDB 实例。 使用 Flask,我现在想在网页上列出数据库的所有项目,并使用第二个网页触发脚本添加其他项目。

但是每次我在“/add”页面上单击“提交”时,我都会收到“不允许的方法”,我可以看到,它尝试将其提交到“/”而不是“/add”..

脚本.py

from flask import Flask, render_template, request
import requests, json, sys, getopt, smtplib
from os import system, name
from pathlib import Path
from pymongo import MongoClient

client = MongoClient(port = 27017)
db = client.amazonProducts
allitems = []
allMyItems = []
for document in db.items.find():
  allitems.append(document["name"])

def addItem():
    for dbWishList in db.wishlist.find():
        url = dbWishList["wishlist"]
    items = json.loads(requests.get(url).text)

    if items:

        for item in items:
            itemName = str(item["name"])
            itemPrice = item["new-price"]
            itemUrl = str(item['link'])
            if itemPrice:
                itemPrice = str(itemPrice[26: ])
                itemPrice = str(itemPrice[: itemPrice.find("<")])
                itemPriceF = str(itemPrice.replace(".", ""))
                itemPriceF = str(itemPriceF.replace("€", ""))
                itemPriceF = str(itemPriceF.replace("\xa0", ""))
                itemPriceF = str(itemPriceF.replace(",", ".")).replace("\xf6", "")
                itemPriceFi = float(itemPriceF)
                itemUrl = itemUrl[: itemUrl.find("?coliid")]
                itemNameF = itemName.replace('&quot;', '"')
                itemNameFi = itemNameF.replace("&amp;amp;", "&")
                itemNameFi = itemNameFi.replace("&uuml;", "ue").replace("&ouml;", "oe").replace("&auml;", "ae").replace("&nbsp;", " ").replace("&ndash;", "-")

            amazonItem = {
                'name': itemNameFi,
                'url': itemUrl,
                'price': itemPriceFi,
                'maxPrice': 0
            }

            db.items.insert_one(amazonItem)

        for document in db.items.find():
            allMyItems.append(document["name"])
        return allMyItems

app = Flask(__name__)

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

  return render_template("index.html", len = len(allitems), allitems = allitems)

app.run(use_reloader = True, debug = True)

app.config["DEBUG"] = True
@app.route("/add", methods = ["GET", "POST"])
def secPage():

    errors = ""
    if request.method == "POST":
        global testingVar
        testingVar = None

        try:
            testingVar = string(request.form["testingVar"])
        except:
            errors += "<p>{!r} is not a string.</p>\n".format(request.form["testingVar"])
        if testingVar is not None:
            addItem()
        return render_template("secIndex.html", len = len(allMyItems), allMyItems = allMyItems)
    return '''
        <html>
            <body>
                {errors}
                <p>What you wanna do?:</p>
                <form method="post" action=".">
                    <p><input name="testingVar" /></p>
                    <p><input type="submit" value="Do magic" /></p>
                </form>
            </body>
        </html>
    '''.format(errors=errors)

index.html

<!DOCTYPE html> 

<html> 
    <head> 
        <title>For loop in Flask</title> 
    </head> 
    <body> 

        <ul> 
        <!-- For loop logic of jinja template -->
        {%for i in range(0, len)%} 

            <li>{{allitems[i]}}</li> 
        {%endfor%} 

        </ul> 

    </body> 
</html> 

secIndex.html

<!DOCTYPE html> 

<html> 
    <head> 
        <title>For loop in Flask</title> 
    </head> 
    <body> 

        <!-- For loop logic of jinja template -->
        <form method="post" action=".">
            <p><input name="testingVar" /></p>
            <p><input type="submit" value="Do magic" /></p>
        </form>


    </body> 
</html> 

这些项目的构建方式如下:

amazonItem = {
    'name': itemNameFi,
    'url': itemUrl,
    'price': itemPriceFi,
    'maxPrice': 0
}

这里有人可以关注我并告诉我我的错误可能出在哪里吗?

最佳答案

在您的表单定义中,您有:

<form method="post" action=".">

action 属性需要具有要将 post 请求发送到的端点。就您而言,您想要

<form method="post" action="/add">

如果省略 action 属性,它将向当前页面提交 post 请求,因此如果您从 /add 查看表单,则只需使用

<form method="post">

关于python - 为什么我的表单试图提交到错误的端点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59377264/

相关文章:

python - 为什么 AWS 告诉我 BucketAlreadyExists 却没有?

python - 如何使用python将树莓派连接到另一台PC的数据库

javascript - 我的网站搜索表单的输入字段不接受输入

javascript - 在tumblr中动态更新 "Avatar"

javascript - 有没有一种方法可以将 MongoDB 中的两个数组合并为一个数组?

node.js - Mongoose 中的静态变量可能吗?

python - panda groupby agg 和计算函数一起

html - Div 彼此重叠,底部 div 边缘显示。

javascript - 如何从 Meteor 的列表集合中删除项目?

python - 如果需要两次,只在列表理解中执行一次函数调用