GaodeMapsのAPIインターフェースのリターンアドレスをMongoDBに保存します



Save Api Interface Return Address Gaode Maps Mongodb



Gaodeマップ:
http://ditu.amap.com/service/regeo?longitude=116.3225&latitude=39.94403
http://ditu.amap.com/service/weather?adcode=110000

次の例では、json文字列をPythonオブジェクト(つまり辞書)に変換します。



import requests url = 'http://ditu.amap.com/service/regeo?longitude=116.3225&latitude=39.94403' response = requests.get(url) print(response.text) import json json_dict = json.loads(response.text) print(type(json_dict)) name = json_dict.get('data').get('cross_list')[0].get('name') print(name)

mongodbをインストールし、コマンドを使用します

brew install mongodb

画像



画像

サブディレクトリを再帰的に作成します。

/ User /(ユーザー名)/ mongodb / dbディレクトリがない場合は、最初に作成する必要があります。使用されるコマンドは次のとおりです。



mkdir -p /User/liwei/mongodb/db

オプション-pは、マルチレベルディレクトリを作成できることを意味します。

画像

MongoDBサービスを開始します。

mongod --dbpath /User/liwei/mongodb/db --port 10001

mongodbを開始します:

画像

このコマンドを実行した後は、コンソールの出力に特に注意してください。コンソールで権限が不十分であるとプロンプトが表示された場合は、コマンドmongodb –dbpath / User / liwei / mongodb / db –port10001の前にsudoを追加する必要があります。

import requests import json # pymongo is mainly responsible for interacting with the MongoDB server import pymongo ip = '127.0.0.1' port = 10001 # Note: The variable is of type int # After the connection is successful, the name of the operated database (similar to the 'database' in the relational database) and collection (similar to the 'table' in the relational database) db_name = 'gd_map' collection_name = 'pos_info' # The element in collenction is document, which is the row in the relational database url_1 = 'http://ditu.amap.com/service/regeo?longitude=116.3225&latitude=39.94403' url_2 = 'http://ditu.amap.com/service/weather?adcode=110000' urls = [url_1, url_2] # Connect to Mongodb server mongo_conn = pymongo.MongoClient(ip, port) # Connect to the corresponding database according to the database name db = mongo_conn[db_name] # Find the collection in the connected database according to the corresponding collection name collection = db[collection_name] for url in urls: try: print(url) resp = requests.get(url) json_dict = json.loads(resp.text) # Insert the converted dictionary structure (Python object) as a document into the corresponding collection collection.save(json_dict) except Exception as e: print(e)

コードを指定すると、コンソールに次の情報が表示されます。

画像

次に、mongodb独自のクライアントプログラムmongoを使用して、データが正常に挿入されたかどうかを確認できます。

mongo 127.0.0.1:10001

画像

クライアントソフトウェアのダウンロード:
https://robomongo.org/download

mongodbを閉じる方法:

画像