为什么我收到的是post请求而不是get请求?

2024-04-28 07:53:05 发布

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

我正在使用flask作为后端。每次我从“/api quotes”请求一个post方法时,它也从“/home”请求一个post方法,即使它只有一个get方法。我在浏览器上不断收到错误消息“请求的URL不允许使用该方法”。有没有办法解决这个问题

<Button onClick={() => {axios.post('/api-quotes', {text: predictMessage})}} type="submit">Generate</Button>

这是我的反应表

from flask import Blueprint, render_template, Flask, jsonify, request, g
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_cors import CORS
from flask_session import Session
from datetime import datetime
from sqlalchemy import Column, ForeignKey, Integer, String, desc
import os
import logging 
import random

basedir = os.path.dirname(os.path.abspath(__file__))

app = Flask("__name__")
CORS(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'posts2.db')
app.config['SQLALCHEMY_BINDS'] = {'quotes': 'sqlite:///' + os.path.join(basedir, 'quotes.db')}
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
ma = Marshmallow(app)

class Posts(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    displayName = db.Column(db.String)
    image = db.Column(db.String)
    text = db.Column(db.String)
    username = db.Column(db.String)#, nullable=False)
    verified = db.Column(db.Boolean)
    avatar = db.Column(db.String)
    date_created = db.Column(db.DateTime, default=datetime.utcnow)

    def __init__(self, id, displayName, image, text, username, verified, avatar):
        self.id = id
        self.displayName = displayName
        self.image = image
        self.text = text
        self.username = username
        self.verified = verified
        self.avatar = avatar

class PostsSchema(ma.Schema):
    class Meta:
        fields = ('id', 'displayName', 'image', 'text', 'username', 'verified', 'avatar', 'date_created')

post_schema = PostsSchema()
posts_schema = PostsSchema(many=True)

@app.route("/api", methods = ['GET', 'POST'])
def api():
    if request.method == 'POST':
        id = Posts.query.order_by('id').all()[-1].id + 1
        displayName = request.json['displayName'] 
        print(request.get_json())
        image = request.json['image'] 
        text = request.json['text'] 
        username = request.json['username'] 
        verified = request.json['verified']
        avatar = request.json['avatar']
        new_posts = Posts(id, displayName, image, text, username, verified, avatar)
        db.session.add(new_posts)
        db.session.commit()
        print(db)
        return post_schema.jsonify(new_posts)
    if request.method == 'GET':
        all_posts = Posts.query.order_by(desc(Posts.id))
        result = posts_schema.dump(all_posts)
        return jsonify(result)

class Quotes(db.Model):
    __bind_key__ = 'quotes'
    id = db.Column(db.Integer, primary_key=True)
    category = db.Column(db.String)
    text = db.Column(db.String)
    date_created = db.Column(db.DateTime, default=datetime.utcnow)

    def __init__(self, id, category, text):
        self.id = id
        self.category = category
        self.text = text

class QuotesSchema(ma.Schema):
    class Meta:
        fields = ('id', 'category', 'text')

quote_schema = QuotesSchema()
quotes_schema = QuotesSchema(many=True)

@app.route("/api-quotes", methods = ['GET', 'POST'])
def apiquotes():
    items = ['Good days will come.', 'Keep calm and carry on!',
    'Treat others the way you want to be treated', 'Life is meaningless without happiness',
    'They may have talent, but you have determination']
    if request.method == 'POST':
        print("Post request to quotes")
        id = Quotes.query.order_by('id').all()[-1].id + 1
        category = 'quotes' 
        text = items[random.randrange(len(items))]
        new_quotes = Quotes(id, category, text)
        print("Inserting to new_quotes")
        db.session.add(new_quotes)
        print("Added new quotes")
        db.session.commit()
        print("Returning quotes")
        print(new_quotes)
        print(quote_schema.jsonify(new_quotes))
        return quote_schema.jsonify(new_quotes)
    if request.method == 'GET':
        print("Sending get to quotes")
        all_quotes = Quotes.query.order_by(desc(Quotes.id))
        result = quotes_schema.dump(all_quotes)
        return jsonify(result)

@app.route("/home", methods = ['GET'])
def my_index():
    print("Getting /home")
    return render_template('index.html')

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

Tags: textimageimportselfidappnewdb
1条回答
网友
1楼 · 发布于 2024-04-28 07:53:05

我怀疑问题在于您的HTML/javascript/react代码。您的问题中没有所有的html,但我认为它看起来会像这样:

<form method=POST>
<button onclick="console.log('posting your api')" type=submit>Press Me</button>
</form>

您可能在表单中有一个按钮。当您单击该按钮时,onclick js将按照您的预期进行发布

如果设置了要提交的类型,则按钮可能连接到某个表单。表单可能被配置为发布到当前页面,我猜当前页面是/home

相关问题 更多 >