如何将从网址中检索到的数据保存到我的数据库中

时间:2016-03-20 11:21:25

标签: python django

我想将网址检索到的城市数据保存到django的sqlite数据库中。 我想存储一个国家每个州的所有城市的数据。 我想编写一个脚本,以便可以从URL解析所有数据并将其存储到我的数据库中。 我已经为一个id = 5,

的州粘贴了一个网址

http://lab.iamrohit.in/php_ajax_country_state_city_dropdown/api.php?type=getCities&stateId=5

此网址显示的数据是

{"status":"success","tp":1,"msg":"Cities fetched successfully.","result":{"448":"Amarpur","449":"Ara","450":"Araria","451":"Areraj","452":"Asarganj","453":"Aurangabad","454":"Bagaha","455":"Bahadurganj","456":"Bairgania","457":"Bakhtiyarpur","458":"Banka","459":"Banmankhi","460":"Bar Bigha","461":"Barauli","462":"Barauni Oil Township","463":"Barh","464":"Barhiya","465":"Bariapur","466":"Baruni","467":"Begusarai","468":"Behea","469":"Belsand","470":"Bettiah","471":"Bhabua","472":"Bhagalpur","473":"Bhimnagar","474":"Bhojpur","475":"Bihar","476":"Bihar Sharif","477":"Bihariganj","478":"Bikramganj","479":"Birpur","480":"Bodh Gaya","481":"Buxar","482":"Chakia","483":"Chanpatia","484":"Chhapra","485":"Chhatapur","486":"Colgong","487":"Dalsingh 

这是字典类型数据

我写了这段代码

def save(self, *args, **kwargs):
        r=requests.get('http://lab.iamrohit.in/php_ajax_country_state_city_dropdown/api.php?type=getCities&stateId=5')
        data=r.json()
        print "data is here",data['stateid']
        super(Country, self).save(*args, **kwargs)

提前致谢

1 个答案:

答案 0 :(得分:1)

因为你没有为城市提供模型,我自己写了:

class State(models.Model):
    name = models.CharField(max_length=255)
    # id from external source, e.g. 5 from your example
    external_id = models.IntegerField()

    def fetch_cities_from_network(self):
        # Fetching data
        resp = requests.get(
            'http://lab.iamrohit.in/php_ajax_country_state_city_dropdown/'
            'api.php?type=getCities&stateId=%d' % self.external_id
        )

        # Get dictionary with cities
        cities_dict = resp.json()['result']

        # Get dictionary values (city names) and save them into the db
        for city in cities_dict.values():
            City.objects.create(state=self, name=city)


class City(models.Model):
    state = models.ForeignKey(State)
    name = models.CharField(max_length=255)

这就是你如何使用它:

state = State.objects.create(name='Some state', external_id=5)
state.fetch_cities_from_network()