关于python:’NoneType’对象不可订阅

'NoneType' object is not subscriptable

本问题已经有最佳答案,请猛点这里访问。

我正在创建一个使用flask+python编写的服务器的iOS应用程序,当我与服务器建立连接以注册用户时,在server.py文件中不断得到"nonetype"对象是不可订阅的错误。基本上,我的问题是什么导致了这个错误,以及我如何修复这个错误。另外,如果有人能给我指出正确的方向,用不同或更简单的方法来做这件事,我会感激的,谢谢!

这是server.py文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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)

这是我在Swift中的注册功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@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 =""



}

回溯:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  [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函数:

1
2
3
4
5
6
7
8
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
}


您需要将content-type明确设置为application/json,以便request.json在烧瓶中正常工作。如果没有设置头部,request.json将不返回任何信息。

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

在使用ios应用程序之前,我还建议您使用nifty请求模块测试API。

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

它已经设置了执行json请求所需的适当头文件。

如果它与requests模块一起工作,那么您可以确定它将与您的iOS应用程序一起工作。您只需确保设置正确的content-type

您可以强制告诉flask忽略content-type

埃多克斯1〔10〕