当前位置: 首页 > 知识库问答 >
问题:

“非类型”对象不可下标[重复]

孙阳舒
2023-03-14

我正在创建一个ios应用程序,它使用一个用flask python编写的服务器,当我连接到服务器注册一个用户时,我的服务器中不断出现一个“NoneType”对象不可订阅错误。py文件。基本上,我的问题是,是什么导致了这个错误,以及我如何能够修复这个错误。此外,如果有人能为我指出不同或更简单的方法的正确方向,我将不胜感激,谢谢!

这是服务器。py文件:

import bcrypt
from flask import Flask, request, make_response,jsonify
from flask_restful import Resource, Api
from pymongo import MongoClient
from json import JSONEncoder
from bson.objectid import ObjectId
from functools import wraps


app = Flask(__name__)

mongo = MongoClient('localhost', 27017)

app.db = mongo.eventure_db

app.bcrypt_rounds = 12

api = Api(app)

# Authentication code.
def check_auth(username, password):
    # check_auth should access the database and check if the username +  password are correct.
    # create a collection to hold the users.

   user_collection = app.db.users
   user = user_collection.find_one({'username': username})

   if user is None:
        return False
    else:
        # check if hash generated matches stored hash
        encodedPassword = password.encode('utf-8')
        if bcrypt.hashpw(encodedPassword, user['password']) == user['password']:
            return True
        else:
            return False



# User resource

class User(Resource):

   def post(self):
        if (request.json['username'] == None
                or request.json['password'] == None):
                return ({'error':  'Request requires username and password'},
                    400,
                    None)

        user_collection = app.db.users
        user = user_collection.find_one({'username':       request.json['username']})

        if user is not None:
            return ({'error': 'Username already in use'}, 400, None)
        else:
            encodedPassword = request.json['password'].encode('utf-8')
            hashed = bcrypt.hashpw(
                encodedPassword, bcrypt.gensalt(app.bcrypt_rounds))
            request.json['password'] = hashed
            user_collection.insert_one(request.json)

    @requires_auth
    def get(self):
        return (None, 200, None)


api.add_resource(User, '/eventure/api/v1.1/user/')

# Must define a custom JSON Serializer for flask_restful
# this is because ObjectId is not a string, and therefore,
# Flask's default serializer cannot serialize it.

@api.representation('application/json')
def output_json(data, code, headers=None):

    resp = make_response(JSONEncoder().encode(data), code)
    resp.headers.extend(headers or {})
        return resp



if __name__ == '__main__':
    app.config['TRAP_BAD_REQUEST_ERRORS'] = True
    app.run(host='localhost', port=8789, debug=True)

这是我在swft中的寄存器函数:

@IBAction func register(_ sender: AnyObject) {

    let url = URL(string: "http://localhost:8789/eventure/api/v1.1/user/")

    var request = URLRequest(url: url!)

    request.httpMethod = "POST"

    request.setValue(generateBasicAuthHeader(username: username.text!, password: password.text!), forHTTPHeaderField: "Authorization")


    let session = URLSession.shared

    let task = session.dataTask(with: request) { data, response, error in
        if let response = response, let data = data {
            print(String(data: data, encoding: String.Encoding.utf8))
        }
    }

    task.resume()




    self.username.text = ""
    self.password.text = ""



}

回溯:

  [28/Oct/2016 19:22:33] "POST /eventure/api/v1.1/user/ HTTP/1.1" 500 -
  Traceback (most recent call last):
  File "/Users/Dynee/eventure-backend-api/development/lib/python3.5/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/Dynee/eventure-backend-api/development/lib/python3.5/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Users/Dynee/eventure-backend-api/development/lib/python3.5/site-packages/flask_restful/__init__.py", line 270, in error_router
    return original_handler(e)
  File "/Users/Dynee/eventure-backend-api/development/lib/python3.5/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/Dynee/eventure-backend-api/development/lib/python3.5/site-packages/flask/_compat.py", line 32, in reraise
    raise value.with_traceback(tb)
  File "/Users/Dynee/eventure-backend-api/development/lib/python3.5/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/Dynee/eventure-backend-api/development/lib/python3.5/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/Dynee/eventure-backend-api/development/lib/python3.5/site-packages/flask_restful/__init__.py", line 270, in error_router
    return original_handler(e)
  File "/Users/Dynee/eventure-backend-api/development/lib/python3.5/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/Dynee/eventure-backend-api/development/lib/python3.5/site-packages/flask/_compat.py", line 32, in reraise
    raise value.with_traceback(tb)
  File "/Users/Dynee/eventure-backend-api/development/lib/python3.5/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/Dynee/eventure-backend-api/development/lib/python3.5/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/Dynee/eventure-backend-api/development/lib/python3.5/site-packages/flask_restful/__init__.py", line 471, in wrapper
    resp = resource(*args, **kwargs)
  File "/Users/Dynee/eventure-backend-api/development/lib/python3.5/site-packages/flask/views.py", line 84, in view
    return self.dispatch_request(*args, **kwargs)
  File "/Users/Dynee/eventure-backend-api/development/lib/python3.5/site-packages/flask_restful/__init__.py", line 581, in dispatch_request
    resp = meth(*args, **kwargs)
  File "/Users/Dynee/eventure-backend-api/server.py", line 128, in post
    if (request.json['username'] == None
TypeError: 'NoneType' object is not subscriptable

这里还有GenerateBasicAuthHeader函数:

func generateBasicAuthHeader(username: String, password: String) -> String {

    let loginString = String(format: "%@:%@", username, password)
    let loginData = loginString.data(using: String.Encoding.utf8)!
    let base64LoginString = loginData.base64EncodedString()
    let basicAuthHeader = "Basic \(base64LoginString)"
    return basicAuthHeader
}

共有1个答案

宋琛
2023-03-14

您需要显式地将内容类型设置为应用程序/json,以便request.json在烧瓶中正常工作。如果没有设置标头,request.json将返回无。

但是,建议使用request.get_json()从post请求获取烧瓶中的json数据。

我还敦促您在使用ios应用程序之前,使用nifty requests模块测试api。

>>> import requests
>>> requests.post(url, json={'name': 'hello world'})

它已经设置了发出json请求所需的适当标头

如果它与请求模块一起工作,那么您可以确定它将与您的ios应用程序一起工作。您只需确保设置了正确的内容类型

您可以强制告诉烧瓶忽略内容类型标头

request.get_json

 类似资料:
  • 问题内容: 基本上,我有一个输入,用户会将数字值(浮动输入)放入其中,然后将所有这些上述列表索引设置为该值。出于某种原因,我无法在没有设置的情况下设置它们: 错误。我是在做错事还是只是以错误的方式看待它? 问题答案: 是一个花车。正在尝试访问浮点数的第一个元素。相反,做 要么

  • 问题内容: 错误 :Tkinter回调跟踪中的异常(最近一次调用最近):文件“ /tools/python/2.7.2/lib/python2.7/lib- tk/Tkinter.py”,行1410,在 调用 返回self.func( * args)填充listb.pop [0]中的文件“ ./edit.py”,第581行,TypeError:’builtin_function_or_method

  • 问题内容: 我有一个标记文件/标记格式的标记文件,并且尝试了一个函数,该函数返回带有(单词,标签)列表中单词的元组。 在python 2.7中效果很好,但是在python 3.4中,它给了我以下错误: 有人可以帮忙吗? 问题答案: 在Python 2中,返回一个列表。在Python 3中,返回一个可迭代的对象。但是您只需调用即可将其放入列表,如: 在这种情况下,将是: 通过列表,您可以使用索引:

  • 这里需要一些帮助来消除这个错误。这是代码-#是运行出色的原始代码,我试图适应: 以下是错误消息: 文件“”,第14行,y=df.loc[df['Adj Close']] 文件"C:\用户\apros\Anaconda3\lib\site-包\熊猫\核心\indexing.py",第1424行,在getitem返回自己。_getitem_axis(maybe_callable,轴=轴) 文件“C:\

  • 问题内容: 为什么以下脚本会给出错误: 问题答案: 在Python 3中,返回类型为的可迭代对象,而不是可下标的列表,该列表允许您编写。要强制列出结果,请写 但是,在许多情况下,您可以不使用索引来更好地编写代码。例如,使用列表推导:

  • 我正在尝试删除空行。但是,当我试图计算空行数以查看它是否有效时,我有一个错误: AttributeError:“非类型”对象没有属性“isnull” 我的剧本: 输出: Traceback(最近的调用最后): 打印文件“\data\u vis.py”,第12行(data\u not\u empty.isnull().sum()) AttributeError:“非类型”对象没有属性“isnull”