TypeError:“位置”类型的对象不可JSON序列化

时间:2019-12-20 13:19:13

标签: python-3.x mongodb flask geopy flask-pymongo

我正在为我的Flask网络应用程序使用 geopy 库。我想将我从模态(html表单)获取的用户位置保存在数据库中(我正在使用mongodb),但是每次我都遇到此错误: TypeError:“ Location”类型的对象不可JSON序列化

代码如下:

@app.route('/register', methods=['GET', 'POST'])
def register_user():
    if request.method == 'POST':
        login_user = mongo.db.mylogin
        existing_user = login_user.find_one({'email': request.form['email']})
        # final_location = geolocator.geocode(session['address'].encode('utf-8'))
        if existing_user is None:
            hashpass = bcrypt.hashpw(
                request.form['pass'].encode('utf-8'), bcrypt.gensalt())
            login_user.insert({'name': request.form['username'], 'email': request.form['email'], 'password': hashpass, 'address': request.form['add'], 'location' : session['location'] })
            session['password'] = request.form['pass']
            session['username'] = request.form['username']
            session['address'] = request.form['add']
            session['location'] = geolocator.geocode(session['address'])
            flash(f"You are Registerd as {session['username']}")
            return redirect(url_for('home'))
        flash('Username is taken !')
        return redirect(url_for('home'))
    return render_template('index.html')

请帮助,如果您需要更多信息,请告诉我。

2 个答案:

答案 0 :(得分:0)

根据geolocator documentation地理代码函数“按地址返回位置点” geopy.location.Location对象。

默认情况下,Json序列化支持以下类型:

  

Python | JSON

     

dict |对象

     

列表,元组|数组

     

str,unicode |字符串

     

int,长整型|数字

     

是|是

     

错误|错误

     

无|空

所有其他对象/类型默认情况下均未进行json序列化,因此您需要对其进行定义。

  

geopy.location.Location.raw

     

位置的原始,未解析的地址解析器响应。有关此的详细信息,   请查阅服务文档。

     

返回类型:dict或None

您也许可以调用Location的原始函数(geolocator.geocode返回值),并且该值可以json序列化。

答案 1 :(得分:0)

Location的确不是json可序列化的:此对象中有许多属性,并且没有表示位置的单一方法,因此您必须自己选择一个。

您希望在响应的location键中看到哪种类型的值?

以下是一些示例:

文本地址

In [9]: json.dumps({'location': geolocator.geocode("175 5th Avenue NYC").address})
Out[9]: '{"location": "Flatiron Building, 175, 5th Avenue, Flatiron District, Manhattan Community Board 5, Manhattan, New York County, New York, 10010, United States of America"}'

点坐标

In [10]: json.dumps({'location': list(geolocator.geocode("175 5th Avenue NYC").point)})
Out[10]: '{"location": [40.7410861, -73.9896298241625, 0.0]}'

原始命题响应

(假设您想保留将来将地理编码服务更改为另一种(可能具有不同的raw响应模式的能力),这不是您要在API中公开的内容。

In [11]: json.dumps({'location': geolocator.geocode("175 5th Avenue NYC").raw})
Out[11]: '{"location": {"place_id": 138642704, "licence": "Data \\u00a9 OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright", "osm_type": "way", "osm_id": 264768896, "boundingbox": ["40.7407597", "40.7413004", "-73.9898715", "-73.9895014"], "lat": "40.7410861", "lon": "-73.9896298241625", "display_name": "Flatiron Building, 175, 5th Avenue, Flatiron District, Manhattan Community Board 5, Manhattan, New York County, New York, 10010, United States of America", "class": "tourism", "type": "attraction", "importance": 0.74059885426854, "icon": "https://nominatim.openstreetmap.org/images/mapicons/poi_point_of_interest.p.20.png"}}'

文本地址+点坐标

In [12]: location = geolocator.geocode("175 5th Avenue NYC")
    ...: json.dumps({'location': {
    ...:     'address': location.address,
    ...:     'point': list(location.point),
    ...: }})
Out[12]: '{"location": {"address": "Flatiron Building, 175, 5th Avenue, Flatiron District, Manhattan Community Board 5, Manhattan, New York County, New York, 10010, United States of America", "point": [40.7410861, -73.9896298241625, 0.0]}}'