简体   繁体   中英

How to make asynchronous Requests in Python

I've been working on a Django app in which I have a page where users can enter in strings in a form (for a query) which will be concatenated to the url using an api for getting concert data. I tried to request the urls using ajax, but apparently the server for the api doesn't allow the client to request the data, meaning that this will have to be done on the server side in python.

I've looked at some SO posts like this one and this other one but they both seem to have solutions that can be implemented when using python in a general way or without the use of a framework. How should I go about requesting this data on the server side within Django?

EDIT:

With the following code, I've been getting a 400 error for some reason. All that is done in the view is the request to the site based on the input from the form. I was just testing whether or not the variables could be concatenate to the URL but the code does seem to be set up so that the form data will be posted when the user clicks submit as I have another view with the same strucuture that sends an email with the form variables, so I'm not sure why this isn't working.

function from views.py:

def search(request):
    form = SearchForm(request.POST or None)
    if form.is_valid():
        form_artistSelect = form.cleaned_data.get("artist_select")
        form_city = form.cleaned_data.get("city")
        form_state = form.cleaned_data.get("state")
        mile_radius = form.cleaned_data.get("radius")
        print "testing"
        url = "http://api.bandsintown.com/events/search?artists[]=" + form_artistSelect + "&location=" +form_city+","+ form_state+"&radius="+ mile_radius + "&format=json&app_id=YOUR_APP_ID"
        data = json.load(urllib2.urlopen(url))
        print data
    context = {

        "form" : form
    }
    return render(request,"searchform.html" , context)

attributes of the form used on the page

class SearchForm(forms.Form):
    artist_select = forms.CharField()
    city = forms.CharField()
    state = forms.CharField()
    radius = forms.CharField()

Try this, I think the problem could be invalid characters in the url:

form_artistSelect = urllib2.quote(form.cleaned_data.get("artist_select"))
form_city = urllib2.quote(form.cleaned_data.get("city"))
form_state = urllib2.quote(form.cleaned_data.get("state"))
mile_radius = urllib2.quote(form.cleaned_data.get("radius"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM