def add_collections_photo(req): if req.method == 'GET': collection_id = int(req.GET.get('id', "1")) current_method = int(req.GET.get('method', 1)) total_photos = get_total_photos_curated(collection_id) current_page = 1 total_page = int(total_photos) / 10 success = 0 failure = 0 if total_page == 0: total_page = 1 #safe value, in case total photo is less than default loading print("for current method : " + str(current_method) + " < total page " + str(total_page) + " current page " + str(current_page) + " for total photos " + str(total_photos)) while (current_page <= 2): if current_method == 1: #this is curated url curated_photo_feed = requests.get(UNSPLASH_BASE_URL + 'collections/curated/' + str(collection_id) + '/photos/?client_id=' + BEYBLADE_ID + '&page=' + str(current_page)) else: #this is featured collection curated_photo_feed = requests.get(UNSPLASH_BASE_URL + 'collections/' + str(collection_id) + '/photos/?client_id=' + BEYBLADE_ID + '&page=' + str(current_page)) curated_collection_photo = curated_photo_feed.json() for counter in range(0, len(curated_collection_photo)): try: status_flag = single_photo_details( curated_collection_photo[counter], counter, str(collection_id), "", "", True) if status_flag: success += 1 else: failure += 1 except ValueError as error: print(" ||ERRor for|| " + str(counter) + " error is " + str(error)) print("Current Method -> " + str(current_method) + " Total Success: " + str(success) + " total failure " + str(failure) + " for page " + str(current_page)) current_page += 1 return HttpResponse("Hello Collections " + "%s%s\n" + "Current Method -> " + str(current_method) + " success -> " + str(success) + " failure -> " + str(failure))
def explore_host_action(request): context = {} if request.method == "GET": url = "https://mysterious-retreat-42657.herokuapp.com/WebApplication?parameter=getAllHostPost" # url = "http://localhost:8080/WebApplication/WebApplication?parameter=getAllHostPost" r = requests.get(url) content = r.text if content.__str__().__len__() != 0: res = eval(content.__str__()) context["length"] = len(res) context["res"] = res print(len(res)) print(res) else: context["length"] = 0 uname = str(request.user.username) print(uname) context["Username"] = mark_safe(json.dumps(uname)) return render(request, "Ucook/explore-host.html", context) if request.method == "POST": try: foodType = request.POST["foodType"] extraInformation = request.POST["extraInformation"] date = "20190409" url = ( "https://mysterious-retreat-42657.herokuapp.com/WebApplication?parameter=newGuestPost&" # "http://localhost:8080/WebApplication/WebApplication?parameter=newGuestPost^" + foodType + "&" + extraInformation + "&" + date) print("url " + url) # print("foodType "+request.POST['foodType']) # print("extraInformation "+extraInformation) r = requests.get(url) # r.json() print(r) url = "https://mysterious-retreat-42657.herokuapp.com/WebApplication?parameter=getAllHostPost" # url = "http://localhost:8080/WebApplication/WebApplication?parameter=getAllHostPost" r = requests.get(url) content = r.text if content.__str__().__len__() != 0: res = eval(content.__str__()) context["length"] = len(res) context["res"] = res else: context["length"] = 0 uname = str(request.user.username) print(uname) context["Username"] = mark_safe(json.dumps(uname)) return render(request, "Ucook/explore-host.html", context) except: context[ "error"] = "You didn't fill out all the blanks, please try again" return render(request, "Ucook/explore-host.html", context)
def index(request): if request.method == 'POST': addr = request.POST['addr'] res2 = requests.get('https://cryptowat.ch/') soup2 = bs4.BeautifulSoup(res2.text, 'lxml') live_price = soup2.find_all('span', {'class': 'price'}) live_bitcoin_price = live_price[1].getText() live_bitcoin_price1 = live_price[1].getText() res = requests.get('https://www.blockchain.com/btc/address/' + addr) if res: soup = bs4.BeautifulSoup(res.text, 'lxml') # bal = soup.find_all('span', {'class': 'sc-1ryi78w-0 bFGdFC sc-16b9dsl-1 iIOvXh u3ufsr-0 gXDEBk'}) bal = soup.find_all('span', { 'class': 'sc-1ryi78w-0 gCzMgE sc-16b9dsl-1 kUAhZx u3ufsr-0 fGQJzg' }) bal[4].getText() final_bal = bal[4].getText() final_bal1 = final_bal.replace(" ", "").rstrip()[:-3].upper() transactions = bal[1].getText() total_received = bal[2].getText() total_received1 = total_received.replace(" ", "").rstrip()[:-3].upper() total_sent = bal[3].getText() total_sent1 = total_sent.replace(" ", "").rstrip()[:-3].upper() final_bal1_int = float(final_bal1) total_received1_int = float(total_received1) total_sent1_int = float(total_sent1) live_bitcoin_price1_int = float(live_bitcoin_price1) balance_usd = final_bal1_int * live_bitcoin_price1_int total_received_usd = total_received1_int * live_bitcoin_price1_int total_sent_usd = total_sent1_int * live_bitcoin_price1_int else: return redirect('/') detail = Details() detail.balance = final_bal detail.balance1 = final_bal1 detail.transactions = transactions detail.total_received = total_received detail.total_received1 = total_received1 detail.total_sent = total_sent detail.total_sent1 = total_sent1 detail.live_bitcoin_price = live_bitcoin_price detail.live_bitcoin_price1 = live_bitcoin_price1 detail.balance_usd = int(balance_usd) detail.total_received_usd = int(total_received_usd) detail.total_sent_usd = int(total_sent_usd) else: detail = ' ' return render(request, 'index.htm', {'detail': detail})
def get_info(self): # 第一步获取code跟state try: self.code = self.request.GET.get("code") self.state = self.request.GET.get("state") except Exception as e: print('获取参数错误') # 2.通过code换取网页授权access_token try: url = u'https://api.weixin.qq.com/sns/oauth2/access_token' params = { 'appid': self.appid, 'secret': self.appsecret, 'code': self.code, 'grant_type': 'authorization_code' } res = requests.get(url, params=params).json() access_token = res["access_token"] # 只是呈现给大家看,可以删除这行 openid = res["openid"] # 只是呈现给大家看,可以删除这行 except Exception as e: print('获取access_token参数错误') raise Http404() # 3.如果access_token超时,那就刷新 # 注意,这里我没有写这个刷新功能,不影响使用,如果想写的话,可以自己去看文档 # 4.拉取用户信息 try: user_info_url = u'https://api.weixin.qq.com/sns/userinfo' params = { 'access_token': res["access_token"], 'openid': res["openid"], } res = requests.get(user_info_url, params=params).json() """ 注意,这里有个坑,res['nickname']表面上是unicode编码, 但是里面的串却是str的编码,举个例子,res['nickname']的返回值可能是这种形式 u'\xe9\x97\xab\xe5\xb0\x8f\xe8\x83\x96',直接存到数据库会是乱码.必须要转成 unicode的编码,需要使用 res['nickname'] = res['nickname'].encode('iso8859-1').decode('utf-8') 这种形式来转换. 你也可以写个循环来转化. for value in res.values(): value = value.encode('iso8859-1').decode('utf-8') """ except Exception as e: print('拉取用户信息错误') # 保存到数据库及登录 # 返回的数据全部在res字典中
def get_posts(title, content): url = 'http://127.0.0.1:8000/posts/' params = {'title': title, 'content': content} r = requests.get(url, params=params) posts = str(r) post_list = {'posts': posts['results']} return post_list
def chip_info(request): findstr = request.GET.get("chip_id") page = requests.get("%s%s" % (CHIP_INFO_BASE_URL, findstr)) tree = html.fromstring(page.content) dog_chip_info = dict() name = tree.xpath('//*[@id="results"]/ul/li[1]/div/text()') if len(name) == 0: dog_chip_info['name'] = "None" else: dog_chip_info['name'] = name[0] dog_chip_info['type_name'] = tree.xpath('//*[@id="results"]/ul/li[3]/div/div')[0].text_content() dog_chip_info['birth_date'] = tree.xpath('//*[@id="results"]/ul/li[7]/div/div')[0].text_content() dog_chip_info['last_kalevet'] = tree.xpath('//*[@id="results"]/ul/li[9]/div/div')[0].text_content() dog_chip_info['is_castrated'] = tree.xpath('//*[@id="results"]/ul/li[5]/div/div')[0].text_content() dog_chip_info['owner_name'] = tree.xpath('//*[@id="results"]/ul/li[10]/div/div/a')[0].text_content() dog_chip_info['owner_phone'] = tree.xpath('//*[@id="results"]/ul/li[11]/div/div[1]')[0].text_content() dog_chip_info['color'] = tree.xpath('//*[@id="results"]/ul/li[4]/div/div')[0].text_content() address = "" for item in tree.xpath('//*[@id="results"]/ul/li[12]/div/div'): address += item.text_content() address += " " dog_chip_info['owner_address'] = address print dog_chip_info context = RequestContext(request, {'dog_chip_info': dog_chip_info}) return render(request, 'app/chip_info.html', context)
def get_symbol(symbol): symbol_list = requests.get( "http://chstocksearch.herokuapp.com/api/{}".format(symbol)).json() for x in symbol_list: if x['symbol'] == symbol: return x['company']
def post_guest_action(request): assert request.method == "POST" context = {} form = GuestPostForm(request.POST or None) # if not form.is_valid(): # return HttpResponseRedirect(request.META.get("HTTP_REFERER")) context = {} if request.method == "GET": return render(request, "Ucook/post-guest.html", context) if request.method == "POST": # try: user = request.user foodType = request.POST["foodType"] extraInformation = request.POST["extraInformation"] date = getIntDate(request.POST['month'], request.POST['day']) url = "https://mysterious-retreat-42657.herokuapp.com/WebApplication?" query_str = "parameter=newGuestPost&foodType=" + foodType + \ "&extraInformation=" + extraInformation + "&preferDate=" + date + \ "&owner=" + user.username url += query_str print(url) r = requests.get(url) print(r.text) return redirect(reverse("exploreHost"))
def comment_action(request): context = {} if request.method == 'GET': return render(request, "Ucook/comment.html", context) if request.method == "POST": print("user", request.user.username) try: comment = request.POST["contact-message"] print("message", comment) rate = request.POST["rating"] print("rate", rate) url = ( "https://mysterious-retreat-42657.herokuapp.com/WebApplication?parameter=makeComment&rate=" # "http://localhost:8080/WebApplication/WebApplication?parameter=newGuestPost^" + rate + "&comment=" + comment + "&Username="******"url " + url) r = requests.get(url) print(r) content = r.text if content.__str__().__len__() != 0: res = eval(content.__str__()) context["length"] = len(res) context["res"] = res else: context["length"] = 0 return redirect(reverse("profile")) except: context[ "error"] = "You didn't fill out all the blanks, please try again" return redirect(reverse("profile"))
def get_rate(): #check if we have a stored rate for today oRate = ExchangeRates.objects.filter(Code__exact=currency).filter( RateDate__exact=datetime.date.today()) if not oRate: #create the exchange record if not stored sURL = 'https://free.currencyconverterapi.com/api/v5/convert?q=GBP_' + currency + '&compact=ultra' response = requests.get(sURL) oData = response.json() sKey = 'GBP_' + currency for k, v in oData.items(): try: if k == sKey: rate = float(v) else: rate = float(9999) except: rate = float(9999) new_entry = ExchangeRates(Code=currency, Name='', ExRate=rate, RateDate=datetime.date.today(), user=request.user) new_entry.save() # this will insert return rate else: #get the stored reco rate = oRate[0].ExRate return rate
def welcome_action(request): context = {} if request.method == 'GET': url_host = "https://mysterious-retreat-42657.herokuapp.com/WebApplication?parameter=getAllHostPost" # url_host = "http://localhost:8080/WebApplication/WebApplication?parameter=getAllHostPost" r_host = requests.get(url_host) content_host = r_host.text if content_host.__str__().__len__() != 0: res_host = eval(content_host.__str__()) context['length_host'] = len(res_host) context['res_host'] = res_host context['recent_host'] = res_host[0] else: context['length_host'] = 0 url_guest = "https://mysterious-retreat-42657.herokuapp.com/WebApplication?parameter=getAllGuestPost" # url_guest = "http://localhost:8080/WebApplication/WebApplication?parameter=getAllGuestPost" r_guest = requests.get(url_guest) content_guest = r_guest.text if content_guest.__str__().__len__() != 0: res_guest = eval(content_guest.__str__()) context['length_guest'] = len(res_guest) context['res_guest'] = res_guest else: context['length_guest'] = 0 time = datetime.now() year = '{:02d}'.format(time.year) month = '{:02d}'.format(time.month)[1:2] day = '{:02d}'.format(time.day) if day < "15": print("<") context['time1'] = year + month + day context['time2'] = year + month + "25" else: print(">") if time.month != 12: context['time1'] = year + month + day month = '{:02d}'.format(time.month + 1)[1:2] context['time2'] = year + month + "10" if request.user.is_authenticated: recs = recommender.getUserRecs(request.user.username) else: recs = recommender.getRandomRecs() context['recs'] = recs print(recs) return render(request, "Ucook/index.html", context)
def test_valid_input_graph(self): file_name = "TestValidGraph" test_data = [("class A", "class A", "method1"), ("class B", "class 1", "method2"), ("class C", "class A", "method3")] url = self.test_graph.generate_graph(test_data, "TestValidGraph") request = requests.get(url) self.assertTrue(request.status_code == 200)
def get_mrmy(self): """ 从接口获取名人名言数据,随机选取一条返回,返回json数据. :return:json, 名人名言数据 """ wb_data = requests.get(self.url, params=self.parm) data = wb_data.json() print(data)
def get_api_results(request=None): try: results = requests.get("http://127.0.0.1:5000/api/alldevicesconsumption/").json() except requests.exceptions.ConnectionError: if request: messages.error(request, "API is offline") results = [] return results
def curent_currencies(requset): course = requests.get( 'https://www.nbrb.by/api/exrates/rates/dynamics/145?startdate=2020-10-13&enddate=2020-10-20' ) data = json.loads(course.text) sum_course = 0 for cur_day in data: sum_course += cur_day['Cur_OfficialRate'] return HttpResponse('Курс доллара: ' + str(round((sum_course / 7), 2)))
def jwtrans(jd, wd): BDSERVICE = "http://api.map.baidu.com/geoconv/v1/?coords=%s,%s&from=1&to=5&ak=v2k8lLfAPWz4Qbzy3GedU0TBYTGbhiGc" urlAPI = BDSERVICE % (jd, wd) req = requests.get(urlAPI, timeout=2) content = req.content oResult = json.loads(content.decode()) bdjd = oResult["result"][0]["x"] bdwd = oResult["result"][0]["y"] return bdjd, bdwd
def get_books(api_key, language, page): url = 'https://api.themoviedb.org/3/movie/now_playing' api_key = '1e94de5ed2dc8e3c7ef6674f1d7b6822' language = 'en' page = '1' params = {'api_key': api_key, 'language': language, 'page': page} r = requests.get(url, params=params) movies = r.json() movie_List = {'books': movies['results']} return books_list
def post(self, request): city = request.data.get('city') locationresponse = requests.get(constants.location_url.format(city)).json() if "invalid_access_key" in locationresponse: return HttpResponse("invalid_access_key passed to location url") country = locationresponse["data"][0]["country"] lat = locationresponse["data"][0]["latitude"] lon = locationresponse["data"][0]["longitude"] City.objects.create(cityname=city, latitude=float(lat), longitude=float(lon), country=country) return HttpResponse("city added")
def Index(request, brand): url = "https://newsapi.org/v2/everything?q=" + brand + "&pageSize=6&apiKey=25a911c33c9747ad965eae6348f799f8" response = requests.get(url) content_from_internet = json.loads(response.content) context = { 'data': content_from_internet, } return render(request, 'polls/index.html', context)
def genre_list(): url = 'https://api.themoviedb.org/3/genre/tv/list?api_key=' + TMDB_API + '&language=en-US' response = requests.get(url) results = json.loads(response.text) data = results['genres'] list = [] for x in data: list.append(x) print(list) return list
def get_short_url(long_url): # json request url = 'http://surl.kr/Api/create.php' params = {'type': 'json', 'longUrl': long_url} res = requests.get(url, params=params) # convert json to dictionary res_data = json.loads(res.text) return res_data['shortUrl'] if res_data[ 'status'] == 'success' else res_data['longUrl']
def profile_detail(request, pk=None): if pk: user = User.objects.get(pk=pk) else: user = request.user #Если админ или не зарегестрированный пользователь, то отправлю на страницу ошибки try: soc_user = SocialAccount.objects.get(user=request.user) social_account = SocialAccount.objects.get(provider='vk', user=request.user.pk) social_token = SocialToken.objects.get(account=social_account) #На всякий случай ловим аватарку пользователя try: avatar = soc_user.get_avatar_url() except: avatar = "no" friend_list = requests.get( "https://api.vk.com/method/friends.get?user_id=" + str(soc_user.uid) + "&count=5&fields=nickname,photo_200_orig&v=5.52&access_token=" + str(social_token)).json()["response"]["items"] #Проверяем наличие друзей f_count = len(friend_list) if f_count == 0: friend_list = "no" args = { "user": user, "name": user.first_name, "last_name": user.last_name, "avatar": avatar, "friend_list": friend_list, "f_count": f_count } return render( request, 'vkprofile/profile.html', args, ) except: return render( request, 'vkprofile/error.html', context={"user": request.user}, )
def get(self, request, *args, **kwargs): api_list = get_api_results(request) r = room.objects.all() l = [] for i in r: room_number = room.objects.get(room_no=i.room_no) plug = plugs.objects.filter(room_no=room_number) sum = 0 for j in plug: for k in api_list: if k['DeviceName'] == j.plug_name: sum += k['CurConsp'] l.append({'room_name': i.room_name, 'CurConsp': sum}) room_names, room_consumptions = [], [] for i in range(len(l)): room_names.append(l[i]['room_name']) room_consumptions.append(l[i]['CurConsp']) room_names = str(room_names) for i in range(len(room_consumptions)): room_consumptions[i] = round(room_consumptions[i], 3) powerData = requests.get("http://127.0.0.1:12345/api").json() batteries, solarpanels, grids = [], [], [] for i in range(len(powerData)): powerData[i]['SupplyingPower'] = int(powerData[i]['SupplyingPower']) powerData[i]['CurrentSupplied'] = round(powerData[i]['CurrentSupplied'], 2) if powerData[i]['type'] == 'Battery': powerData[i]['ChargingState'] = int(powerData[i]['ChargingState']) batteries.append(powerData[i]) elif powerData[i]['type'] == 'EnergyGenerator': solarpanels.append(powerData[i]) powerData[i]['ChargingState'] = int(powerData[i]['ChargingState']) elif powerData[i]['type'] == 'Grid': grids.append(powerData[i]) powerData[i]['PowerCut'] = int(powerData[i]['PowerCut']) else: print("No power source connected") return render(request, self.template_name, {"Room": room.objects.all(), "name_rooms": room_names, "consumption_rooms": room_consumptions, "Battery": batteries, "Solarpanel": solarpanels, "Grid": grids, "User_ranking": user_rankings()}, )
def index(req): total_success = 0 total_failure = 0 for page_number in range(1, MAX_LOOP, 1): random_feed = requests.get(UNSPLASH_BASE_URL + 'photos/?client_id=' + BEYBLADE_ID + '&page=' + str(page_number)) if random_feed.text == 'Rate Limit Exceeded': print ("$$$$ ---- LIMIT EXCEEDED ---- $$$$ in " + str(page_number)) html_message = "$$$$ ---- LIMIT EXCEEDED ---- $$$$ in " + str(page_number) \ + " Total Success: " + str(total_success) + " Total Failure: " + str(total_failure) return HttpResponse(html_message) break else: try: feed_array = random_feed.json() except ValueError as error: print ("No JSON file "+str(error)) return HttpResponse(str(error)) for counter in range(0, 10): current_photo_id = feed_array[counter]['id'] photo_details_url = requests.get( UNSPLASH_BASE_URL + 'photos/' + current_photo_id + '?client_id=' + BEYBLADE_ID + '&w=' + str(CUSTOM_WIDTH) + '&h=' + str(CUSTOM_HEIGHT)) if photo_details_url.text == 'Rate Limit Exceeded': print ("$$$$ ---- LIMIT EXCEEDED ---- $$$$ in " + str(page_number)) html_message = "$$$$ ---- LIMIT EXCEEDED ---- $$$$ in " + str(page_number) \ + " Total Success: " + str(total_success) + " Total Failure: " + str(total_failure) return HttpResponse(html_message) break else: flag = single_photo_details(photo_details_url.json(), page_number) if flag: total_success += 1 else: total_failure += 1 print ("Total Success: " + str(total_success) + " Total Failure: " + str(total_failure)) return HttpResponse("Total Success: " + str(total_success) + " Total Failure: " + str(total_failure))
def post(self, request, *args, **kwargs): user = request.user if 'new_device' in request.POST: api_devices_list = get_api_results() # Using generator, get the item from the list that matches the IP provided from front-end. device_data = next(item for item in api_devices_list if item["ip_address"] == request.POST[request.POST['new_device'] + '_ip_address']) plugs.objects.create(plug_name=device_data['DeviceName'], plug_model_name=device_data['DeviceModel'], ip_address=device_data['ip_address'], room_no=room.objects.get(room_no=kwargs['room_no']), # curr_consumption=device_data['CurConsp'], status=False if device_data['status'] == "off" else True) if 'change_status' in request.POST: values = request.POST['change_status'].split(',') requests.get("http://127.0.0.1:5000/api/changestatus/" + values[1]) plug_obj = plugs.objects.get(ip_address=values[0], plug_name=values[1]) if plug_obj.status: plug_obj.status = False else: plug_obj.status = True # plug_obj.status = True if plug_obj.status else False # Adding to the leaderboard leaderboard_info(plug_obj.status, values[1], request.user) plug_obj.save() if 'add_device' in request.POST: plugs.objects.create(plug_name=request.POST['plug_name'], plug_model_name=request.POST['plug_model_name'], ip_address=request.POST['ip_address'], room_no=room.objects.get(room_no=kwargs['room_no'])) if 'remove_device' in request.POST: plugs.objects.filter(plug_no=request.POST.get('plug_no')).delete() return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
def get(self): r = requests.get('http://call.tgju.org/ajax.json') print(r.text) result = json.loads(r.text) dollar_price = result['current']['price_dollar_rl']['p'] dollar_price = dollar_price.split(',') final_dollar_price = '' for i in dollar_price: final_dollar_price = final_dollar_price + i final_dollar_price = int(final_dollar_price)/10 print(final_dollar_price)
def handle(self, *args, **options): self.stdout.write("[*] checking all sites") for site in get_url_list(): try: response = requests.get(site.url) self.stdout.write(site.url + " Response: %s" % response.status_code) site.last_response_code = str(response.status_code) site.last_time_check = timezone.now() site.save() except: self.stdout.write("Unable to get response from " + site.url)
def post_host_action(request): context = {} if request.method == "GET": return render(request, "Ucook/posthost.html", context) # assert request.method == "POST" context = {} # form = HostPostForm(request.POST or None) # if not form.is_valid(): # return HttpResponseRedirect(request.META.get("HTTP_REFERER")) # # call cloud db API # context["content"] = form.cleaned_data # return render(request, "post-host-detail", context) # call cloud db API if request.method == "POST": # try: user = request.user address1 = request.POST["address1"] address2 = request.POST["address2"] postCode = request.POST["postcode"] city = request.POST["city"] state = request.POST["state"] foodType = request.POST["foodType"] extraInformation = (request.POST["extraInformation"]) preferDate = str(getIntDate(request.POST['month'], request.POST['day'])) number = request.POST["number"] coords = gmaps.geocode(address1 + " " + city + " " + state)[0]['geometry']['location'] print(coords) lat = str(coords['lat']) lng = str(coords['lng']) url = "https://mysterious-retreat-42657.herokuapp.com/WebApplication?" query_str = "parameter=newHostPost&address1=" + address1 + \ "&address2=" + address2 + "&postCode=" + str(postCode) + "&city=" + city + "&state=" + state + \ "&foodType=" + foodType + "&extraInformation=" + extraInformation + "&preferDate=" + preferDate + \ "&number=" + str(number) + "&owner=" + user.username + "&lat=" + str(lat) + "&lng=" + str(lng) url += query_str print(url) r = requests.get(url) print(r.text) # # url = "https://protected-plains-77518.herokuapp.com/WebApplication?parameter=getAllGuestPost" # # r = requests.get(url) # content = r.text # res = eval(content.__str__()) # context["length"] = len(res) # context["res"] = res return redirect(reverse("exploreNonHost"))
def search_original(q): url_api_search = 'https://www.googleapis.com/youtube/v3/search' search_params = { 'part': 'snippet', 'key': 'AIzaSyACCLlnn_hlOpNk5XUBpRqs-iZWpbTm-J4', 'maxResults': '10', 'type': 'video', 'q': q, } # YouTube의 search api에 요청, 응답 받음 response = requests.get(url_api_search, params=search_params) # 응답은 JSON형태로 오며, json()메서드로 파이썬 객체 형식으로 변환 data = response.json() return data
def url_retry(url, num_retries=3): try: r = requests.get('http://www.itwhy.org') request = requests.get(url, timeout=60) #raise_for_status(),如果不是200会抛出HTTPError错误 request.raise_for_status() soup = get_soup(url) except request.HTTPError as e: soup = None write_err(e) with open('log.txt', 'a') as f: f.write() if num_retries > 0: #如果不是200就重试,每次递减重试次数,使用函数获取soup数据 return url_retry(url, num_retries - 1) #如果url不存在会抛出ConnectionError错误,这个情况不做重试 except request.exceptions.ConnectionError as e: return except request.exceptions.TimeOut: return return soup
def proxy_to(request, path, target_url): url = '%s%s' % (target_url, path) headers = { } if request.method == 'GET': proxied_response = requests.get(url, headers=headers) elif request.method == 'POST': proxied_response = requests.post(url, data=request.body, headers=headers) elif request.method == 'PUT': proxied_response = requests.put(url, data=request.body, headers=headers) elif request.method == 'DELETE': proxied_response = requests.delete(url, data=request.body, headers=headers) return HttpResponse(proxied_response)
def CreateMedia(user, title, link, des): video_id = link.split('v=')[+1] thumbnail_url = f"http://img.youtube.com/vi/{video_id}/sddefault.jpg" request = requests.get(thumbnail_url, stream=True) lf = tempfile.NamedTemporaryFile() for block in request.iter_content(1024 * 8): if not block: break lf.write(block) media = MediaBlog(author=user) media.title = title media.link = link media.description = des media.thumbnail.save("thumbnail.jpg", files.File(lf))
def test_valid_input_graph(self): file_name = "TestValidGraph" test_data = [("class A", "class A", "method1"), ("class B", "class 1", "method2"), ("class C","class A","method3")] url = self.test_graph.generate_graph(test_data, "TestValidGraph") request = requests.get(url) self.assertTrue(request.status_code == 200)