【问题标题】:Flask view takes 1 positional argument but 2 were given [closed]Flask 视图采用 1 个位置参数,但给出了 2 个 [关闭]
【发布时间】:2021-08-09 20:14:23
【问题描述】:

通常当我遇到takes 1 positional argument but 2 were given 错误时,我会查找我忘记在其中添加self 的情况,但有人可以告诉我为什么 Flask 在这里抱怨

api-server.py:这是一个最小的例子,有 1 个 POST 端点,什么都不做

#!/usr/bin/env python3

# This script simulates the API

import sys
import os
import psycopg2
from psycopg2 import pool
import threading # NOTE Not sure if we need this, especially if Flask is not multithreaded
from flask import Flask
from flask_restplus import Api
from flask_restplus import Resource, reqparse, fields

app= Flask (__name__)
api = Api(
    app = app,
    version = "1.0",
    title = "Test",
    description = "Test")

# Get environment variables
try:
    db_host         = os.environ.get ('DB_HOST', 'localhost')
    db_port         = os.environ.get ('DB_PORT', 5432)
    db_user         = os.environ.get ('DB_USER', 'postgres')
    db_password     = os.environ.get ('DB_PASSWORD', 'postgres')
    db_name         = os.environ.get ('DB_NAME', 'test')
    api_port        = os.environ.get ('API_PORT', 12345)
    api_host        = os.environ.get ('API_HOST', '0.0.0.0')
except Exception as e:
    print ('Could not load all environment variables')
    print (e)
    sys.exit (1)

# Setup DB Connection
try:
    conn_pool = psycopg2.pool.ThreadedConnectionPool (
        1,
        5,
        host        = db_host,
        port        = db_port,
        user        = db_user,
        password    = db_password,
        dbname      = db_name)
except Exception as e:
    print ('Could not establish database connection')
    print (e)
    sys.exit (1)

# NOTE Not sure if we need this
threadLock = threading.Lock()

model = api.model (
    'register_user model',
    {
        'email': fields.String (
            reguired = True,
            description = "Email of the user",
            help = "Email cannot be blank, must be of length 3, can start with an upper or lower case letter, can contain upper/lower case, numbers, and the following special characters [...]",
            example = "john.smith@example.com"
        ),
        'username': fields.String (
            reguired = True,
            description = "Username of the user",
            help = "Username cannot be blank, must be of length 3, can start with an upper or lower case letter, can contain upper/lower case, numbers, and the following special characters [...]",
            example = "john.smith"
        ),
        'password': fields.String (
            reguired = True,
            description = "Password of the user",
            help = "Password cannot be blank, must be of length 3, can start with an upper or lower case letter, can contain upper/lower case, numbers, and the following special characters [...]",
            example = "1 Flew 0ver the c00k00s n&st"
        )
    }
)

@api.route ("/register_user")
class RegisterUserClass (Resource):
    def __init__ (self):
        Resource.__init__ (self)

        ### Argument Parser
        ### - bundle_errors returns all errors, not just the first encountered
        ### - Strict returns error if unknown argument detected
        self.parser = reqparse.RequestParser(
            bundle_errors = True,
            strict = True
        )

        parser.add_argument(
            'email',
            required = True,
            type = inputs.email (dns=True),
            min_length = 1,
            max_length = 4096,
            help = 'Invalid email'
        )

        parser.add_argument(
            'username',
            required = True,
            type = str,
            min_length = 6,
            max_length = 64,
            pattern = '.*',
            help = 'User username'
        )

        parser.add_argument(
            'password',
            required = True,
            type = str,
            min_length = 6,
            max_length = 72,
            pattern = '.*',
            help = 'User password'
        )

    @api.doc(
        responses = {
            200: 'OK',
            400: 'Invalid Argument',
            500: 'Mapping Key Error'
        }
    )
    @api.expect (model)
    def post (self):
        pass

app.run(host=api_host, port=api_port)

我这样调用端点

import http.client
    
api = http.client.HTTPConnection(
            host=api_host,
            port=api_port
        )

params = json.dumps({
        'email': 'john.smith@example.com',
        'username': 'john.smith',
        'password': 'password123'
    })

headers = {
    "Content-type" : "application/json",
    "Accept"       : "text/plain"
}    
try:
    settings.api.request(
        method  = 'POST',
        url     = '/register_user',
        body    = params,
        headers = settings.headers
    )

except Exception as error:
    pass

错误:但我不断收到此错误

 * Serving Flask app "api" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:12345/ (Press CTRL+C to quit)
[2021-08-09 13:03:42,002] ERROR in app: Exception on /register_user [POST]
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/local/lib/python3.8/dist-packages/flask_restplus/api.py", line 325, in wrapper
    resp = resource(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/flask/views.py", line 88, in view
    self = view.view_class(*class_args, **class_kwargs)
TypeError: __init__() takes 1 positional argument but 2 were given
127.0.0.1 - - [09/Aug/2021 13:03:42] "POST /register_user HTTP/1.1" 500 -

【问题讨论】:

    标签: python api flask


    【解决方案1】:

    不应该这样指定你的路线吗?

    @app.route ("register_user")

    目前您已将此指定为 api.route

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-11
      • 1970-01-01
      • 2013-10-28
      • 2020-05-20
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多