Exemple #1
0
def f13():
    try:
        wa = "https://ipinfo.io/"
        res = requests.get(wa)
        print(res)

        data = res.json()
        print(data)

        city_name = data['city']
        print("city_name = ", city_name)

        a1 = "http://api.openweathermap.org/data/2.5/weather?units=metric"
        a2 = "&q=" + city_name
        a3 = "&appid=" + "c6e315d09197cec231495138183954bd"

        wa = a1 + a2 + a3
        res = requests.get(wa)
        print(res)

        data = res.json()
        print(data)

        temp = data['main']['temp']
        print(temp)
        return "Location : " + city_name + "               Temperature : " + str(
            temp)

    except Exception as e:
        showerror('failure', e)
Exemple #2
0
def tqyb(uer):
    url1 = "http://t.weather.sojson.com/api/weather/city/" + uer['city_code']
    re = requests.get(url1)
    tq0 = re.json()["cityInfo"]
    tq = re.json()["data"]["forecast"][0]
    tq1 = re.json()["data"]
    # print("当前城市:"+tq0["parent"],tq0["city"])
    tq00 = "当前城市:" + tq0["parent"], tq0["city"], "今天" + tq["week"], "最" + tq["high"], "最" + tq["low"] \
        , "天气类型:" + tq["type"], tq["fx"], tq["fl"], "温馨提示:" + tq["notice"] \
        , "湿度:" + tq1["shidu"], "空气质量:" + tq1["quality"], "感冒指数:" + tq1["ganmao"], "天气更新时间:" + tq0["updateTime"]
    # print(tq00)
    return str(tq00)
def get_mac_from_code(code):
    print "the code is:", code
    print "the len of code:", len(code)
    if len(code) == 17:
        return code
    else:
        code_tuple = split_code(code)
        ddns_name = get_two_par_from_code_tuple(code_tuple)
        payload = {'action': 'getDeviceInfo', 'ddns_name': ddns_name}
        re = requests.get("http://192.168.16.17/api.php",
                          params=payload)  # 这里面传递过来的参数是什么
        print re.json()[0]
    return re.json()[0]['mac_address']
Exemple #4
0
def wb_back(request):
    #接收参数
    code = request.GET.get('code', None)

    #定义token接口地址
    url = "https://api.weibo.com/oauth2/access_token"

    #定义参数
    re = requests.post(url,
                       data={
                           "client_id": "2949825616",
                           "client_secret": "efcf35e94890965ae1d71eb7b971c693",
                           "grant_type": "authorization_code",
                           "code": code,
                           "redirect_uri":
                           "http://127.0.0.1:8000/md_admin/weibo"
                       })

    print(re.json())

    #换取新浪微博用户昵称
    res = requests.get('https://api.weibo.com/2/users/show.json',
                       params={
                           'access_token': re.json()['access_token'],
                           'uid': re.json()['uid']
                       })

    print(res.json())
    sina_id = ''
    user_id = ''

    # 判断是否用新浪微博登录过
    user = User.objects.filter(username=str(res.json()['name'])).first()

    if user:
        # 代表曾经用该账号登录过
        sina_id = user.username
        user_id = user.id
    else:
        # 首次登录,入库新浪微博账号
        user = User(username=str(res.json()['name']), password='')
        user.save()
        user = User.objects.filter(username=str(res.json()['name'])).first()
        sina_id = user.username
        user_id = user.id

    print(sina_id, user_id)
    # 重定向
    return redirect("http://localhost:8080?sina_id=" + str(sina_id) + "&uid=" +
                    str(user_id))
Exemple #5
0
 def __crud_records(self, record_type, verb, data=None, **kwargs):
     """
     :param verb: HTTP requests verbs GET|POST|PUT|DELETE
     :param record_type: Provider | Collection | PDR ...
     :param data: json data to be ingested
     :return: False in case of error
     """
     allowed_verbs = ['GET', 'POST', 'PUT', 'DELETE']
     if verb.upper() not in allowed_verbs:
         return "{} is not a supported http request".format(verb)
     url = f"{self.INVOKE_BASE_URL}/v1/{record_type}"
     and_sign = ""
     query = ""
     for ele in kwargs.keys():
         query = "{}{}{}={}".format(query, and_sign, ele, kwargs[ele])
         and_sign = "&"
     if kwargs:
         url = "{}?{}".format(url, query)
     re = getattr(requests, verb.lower())(url=url,
                                          json=data,
                                          headers=self.HEADERS)
     try:
         return re.json()
     except Exception as e:
         logging.error("%s" % str(e))
         return re.content
Exemple #6
0
def get_info(jid, lid):
    params = {'jid': jid, 'lid': lid}

    # 获取cookies
    with open('bossCookies.json', 'r', encoding='utf-8') as f:
        listcookies = json.loads(f.read())

    # 把获取的cookies处理成dict类型
    cookies_dict = dict()
    for cookie in listcookies:
        # 在保存成dict时,只要cookies中的name和value
        cookies_dict[cookie['name']] = cookie['value']

    requests.adapters.DEFAULT_RETRIES = 5
    s = requests.session()
    # 关闭多余进程
    s.keep_alive = False
    # 请求ajax获取岗位职责
    re = requests.get(get_url + urlencode(params),
                      headers=headers,
                      cookies=cookies_dict)
    time.sleep(0.2)
    if re.status_code == 200:
        vjson = re.json()
        return vjson
    else:
        print("获取失败")
Exemple #7
0
 def xk(self, index):
     url = "http://202.119.81.112:9080/njlgdx/xk/processXk"
     pars = {
         'jx0502id': self.xk_memory[1],
         'jx0404id': self.xkkc[index][3],
         'jx0502zbid': self.xk_memory[0],
         'xf': self.xkkc[index][4],
         'kch': self.xkkc[index][5],
         'zxs': self.xkkc[index][6],
         'kcsx': '1',
         'szkcfl': '',
         'kkzcmx': self.xkkc[index][9],
         'kcsjmx': self.xkkc[index][10]
     }
     re = self.s.post(url=url, headers=heard1, data=pars)
     text = re.json()
     print(text)
     add_text(text['msgContent'] + ':' + self.xkkc[index][0] + ' ' + self.xkkc[index][1] + ' ' + self.xkkc[index][2],
              parent='tab3')
     a = self.xkkc[index][0]
     b = self.xkkc[index][1]
     c = self.xkkc[index][2]
     self.sel_kc()
     self.paint()
     add_text(re.text + ':' + a + ' ' + b + ' ' + c, parent='tab3')
def inform_finedust(time, location):
    re = requests.get(build_url(time, location))
    rjson = re.json()
    data = rjson['TimeAverageAirQuality']['row']

    for i in range(0, len(data)):
        return {
            "MEASURE_DATE": data[i]['MSRDT'],
            "DISTRICT": data[i]['MSRSTE_NM'],
            "PM10": str(data[i]['PM10']),
            "PM25": str(data[i]['PM25'])
        }
Exemple #9
0
    def establish(self, year, week, team, season="regular"):
        url = f"https://api.collegefootballdata.com/lines?year={year}&week={week}&seasonType={season}&team={team}"
        re = requests.get(url=url, headers=HEADERS)
        data = re.json()

        try:
            self.home_team = data[0]['homeTeam']
            self.home_score = data[0]['homeScore']
            self.away_team = data[0]['awayTeam']
            self.away_score = data[0]['awayScore']
            linedata = data[0]["lines"]

            for line in linedata:
                self.lines.append(
                    GameBetLine(provider=line['provider'],
                                spread=line['spread'],
                                formatted_spread=line['formattedSpread'],
                                over_under=line['overUnder']))
        except:
            pass
Exemple #10
0
def foreach_art_list():
    # 判断目录下是否存在jilv.txt文件 如果存在则读取里面的数值
    if os.path.exists('./jilv.txt'):
        f = open('./jilv.txt')
        n = f.read()
        n = int(n)
        f.close()
    else:
        n = 1    
    while True:
        url = 'http://www.toutiao.com/search_content/?offset=' + str(n) + '&format=json&keyword=%E6%B8%85%E7%BA%AF%E7%BE%8E%E5%A5%B3&autoload=true&count=1&cur_tab=3&from=gallery'
        re = requests.get(url)
        data = re.json()['data']
        if not data:
            break
        # 运行图片下载函数
        download_pic(data[0]['article_url'],n)
        n = n+1
        # 将n写入文件 防止程序运行出错 可以继续运行
        with open('./jilv.txt', 'w') as f:
            f.write(str(n))
Exemple #11
0
def get_theft_points(request):

    # Validate latitude - required, number only
    try:
        latitude = request.GET["latitude"]
        latitude = float(latitude)
    except KeyError:
        return HttpResponseBadRequest("Missing latitude parameter")
    except ValueError:
        return HttpResponseBadRequest("Non-numeric latitude parameter")

    # Validate longitude - required, number only
    try:
        longitude = request.GET["longitude"]
        longitude = float(longitude)
    except KeyError:
        return HttpResponseBadRequest("Missing longitude parameter")
    except ValueError:
        return HttpResponseBadRequest("Non-numeric longitude parameter")

    location_data = {"latitude": latitude, "longitude": longitude, "radius": 0.1}
    re = requests.get("http://127.0.0.1:8100/search", params=location_data)
    return json_response(re.json())
Exemple #12
0
    def request(self,t):
        i = 1
        while True:
            self.params['pageNumber'] = str(i)
            try:
                re = requests.get(self.link,params=self.params,headers=self.headers,cookies=self.cookies,timeout=3.1)
            except Timeout:
                print('json数据请求超时')
                continue
            try:
                text = re.json()['resultList']
            except json.decoder.JSONDecodeError as e:
                print('错误是:' + str(e))
                return
            if text == []:
                break
            for x in text:
                l = []
                # 获取详情页的链接参数
                l.append(x['caseId'])
                l.append(x['title'])
                l.append(x['courtName'])
                l.append(x['caseNo'])
                l.append(x['caseCause'])
                l.append(x['judge'])
                l.append(x['description'])
                l.append(int(x['beginTime'])/1000)
                self.queue.put(l)
            time.sleep(1)
            i += 1
        print('json数据请求完成')

        # 等待所有的详情页请求完结束代码
        if self.queue.join():
            t.join()
            return
Exemple #13
0
    def getPlaylist(self, playlist_id):
        """获取歌单信息
        :params playlist_id:歌单ID
        :return: 歌单所有歌曲的信息<dict>
        """
        url = 'http://music.163.com/api/playlist/detail?id=%s' % playlist_id
        re = requests.get(url, headers=self.headers)

        # 包括歌曲ID 歌曲名 歌手 专辑
        detail = re.json()['result']['tracks']
        music_list = []
        for x in range(len(detail)):
            info = detail[x]
            artists_name = info["artists"][0]['name']
            for i in range(1, len(info["artists"])):
                artists_name += '&' + info["artists"][i]['name']
            music_list.append({
                'song_name': info['name'],
                'artists_name': artists_name,
                'song_album': info['album']['name'],
                'song_id': info['id'],
            })

        return music_list
Exemple #14
0
    def get(self, uri, headers):
        # This method automatically gets ALL resources. Use a filter if less are desired
        log = logging.getLogger(libLogger)
        x = 0
        members = []
        response = {}

        while True:
            try:
                log.debug('\nURL\tGET %s\nHeader %s\n' % (uri, headers))
                re = self._http.get(uri,
                                    auth=self._sessionId,
                                    headers=headers,
                                    verify=False)
                resp = re.json()
                log.debug(
                    '\nStatus %d\nResponse Headers %s\nResponse Body %s' %
                    (re.status_code, re.headers,
                     pprint.PrettyPrinter().pformat(resp)))

                if isinstance(resp, dict):
                    if 'nextPageUri' in resp:
                        if x == 0:
                            response = re.json()
                        else:
                            # add members
                            response['members'] += resp['members']
                        x += 1
                        count = resp['count']
                        total = resp['total']

                        if resp['nextPageUri']:
                            nextPageUri = resp['nextPageUri']
                            uri = string.Template("https://$ip$uri")
                            uri = uri.substitute(ip=self._ip, uri=nextPageUri)
                        else:
                            response['count'] = response['total']
                            break
                    else:
                        response = resp
                        break
                else:
                    break

            except Exception as e:
                msg = "Exception occured while attempting to GET: %s" \
                    % (uri)
                raise Exception(msg, e)

            if re.status_code != 200:
                log.debug('\nResponse Body %s' %
                          pprint.PrettyPrinter().pformat(re.json()))
                msg = "Status %d received from GET %s" \
                    % (re.status_code, uri)
                raise Exception(msg, re.text)
            else:
                log.debug('\nStatus %d\nResponse Body %s' %
                          (re.status_code, pprint.PrettyPrinter().pformat(
                              re.json())))

        return response
Exemple #15
0
 def send_request(self, method, url, data=None, header=None, extract=''):
     """
     :param method: 请求方法
     :param url:  请求url
     :param data:  请求Body
     :param header:  请求头
     :param extract:  对返回结果进行变量提取
     :return: r.json()
     """
     re = None
     re_error = {'msg': '请求失败', 'code': '请求失败'}
     re_type_error = {
         'code': 10001,
         'msg': '返回数据格式不是json,当前框架无法处理,请联系框架开发者--谷哥'
     }
     if method == 'get':
         try:
             re = requests.get(url, headers=header)
         except Exception as e:
             return e
     elif method == 'post':
         if header['Content-Type'] == 'application/x-www-form-urlencoded':
             try:
                 re = requests.post(url, data=data, headers=header)
             except Exception as e:
                 return e
         elif header['Content-Type'] == 'text/xml':
             try:
                 re = requests.post(url, json=data, headers=header)
             except Exception as e:
                 return e
         elif header['Content-Type'] == 'application/json':
             try:
                 re = requests.post(url, json=data, headers=header)
             except Exception as e:
                 return e
         elif header['Content-Type'] == 'multipart/form-data':
             try:
                 del header['Content-Type']
                 re = requests.post(url, data=data, headers=header)
             except Exception as e:
                 return e
         else:
             re = False
     elif method == 'put':
         if header['Content-Type'] == 'application/x-www-form-urlencoded':
             try:
                 re = requests.put(url, data=data, headers=header)
             except Exception as e:
                 return e
         elif header['Content-Type'] == 'text/xml':
             try:
                 re = requests.put(url, json=data, headers=header)
             except Exception as e:
                 return e
         elif header['Content-Type'] == 'application/json':
             try:
                 re = requests.put(url, json=data, headers=header)
             except Exception as e:
                 return e
         elif header['Content-Type'] == 'multipart/form-data':
             try:
                 del header['Content-Type']
                 re = requests.put(url, data=data, headers=header)
             except Exception as e:
                 return e
         else:
             re = False
     elif method == 'delete':
         try:
             re = requests.delete(url, headers=header)
         except Exception as e:
             return e
     elif method == 'patch':
         try:
             re = requests.patch(url, headers=header)
         except Exception as e:
             return e
     print('url:{}\r\nmethod:{}\r\nrequest_data:{}'.format(
         url, method, data))
     if re and re.status_code == 200:
         print('response_code: {}'.format(re.status_code))
         try:
             re_json = re.json()
             print('response:{}'.format(re_json))
             if extract != '':
                 self.operate_json(re_json, extract)
             return re_json
         except:
             print('response:{}'.format(re_type_error))
             return re_type_error
     else:
         print('response_code: {}'.format(re.status_code))
         print(
             'url:{}\r\nmethod:{}\r\nrequest_data:{}\r\nresponse:{}'.format(
                 url, method, data, '请求失败'))
         return re_error
Exemple #16
0
def query_train_info(url, text):
    '''
    查询火车票信息:
    返回 信息查询列表
    '''
    print(url)

    info_list = []
    price_list = []
    try:
        r = requests.get(url, verify=False)

        # 获取返回的json数据里的data字段的result结果
        raw_trains = r.json()['data']['result']

        for raw_train in raw_trains:
            # 循环遍历每辆列车的信息
            data_list = raw_train.split('|')

            # 车次号码
            train_number = data_list[3]
            # 出发站
            from_station_code = data_list[6]
            from_station_name = text['南宁']
            # 终点站
            to_station_code = data_list[7]
            to_station_name = text['北海']
            # 出发时间
            start_time = data_list[8]
            # 到达时间
            arrive_time = data_list[9]
            # 总耗时
            time_fucked_up = data_list[10]
            # 一等座
            first_class_seat = data_list[31] or '--'
            # 二等座
            second_class_seat = data_list[30] or '--'
            # 软卧
            soft_sleep = data_list[23] or '--'
            # 硬卧
            hard_sleep = data_list[28] or '--'
            # 硬座
            hard_seat = data_list[29] or '--'
            # 无座
            no_seat = data_list[26] or '--'

            # 列车序列号
            train_no = data_list[2]
            # 出发站序列号
            from_station_no = data_list[16]
            # 终点站序列号
            to_station_no = data_list[17]
            # 类型
            seat_types = data_list[35] or 'OMO'
            # 列车日期
            train_date = all_data

            # https://kyfw.12306.cn/otn/leftTicket/queryTicketPrice?train_no=77000D179310&from_station_no=11&to_station_no=14&seat_types=OMO&train_date=2018-11-20
            # api url 构造
            price_url = (
                'https://kyfw.12306.cn/otn/leftTicket/queryTicketPrice?'
                'train_no={}&'
                'from_station_no={}&'
                'to_station_no={}&'
                'seat_types={}&'
                'train_date={}').format(train_no, from_station_no,
                                        to_station_no, seat_types, train_date)

            print(price_url)

            re = requests.get(price_url, verify=False)
            ticket_price = re.json()['data']
            print(ticket_price)
            # first_class_seat_price = ticket_price['M']
            # second_class_seat_price = ticket_price['O']
            # no_seat_price = ticket_price['WZ']

            # 打印查询结果
            info = ('车次:{}\n出发站:{}\n目的地:{}'
                    '\n出发时间:{}\n到达时间:{}\n消耗时间:{}\n'
                    '座位情况:\n 一等座:「{}」 \n二等座:「{}」\n软卧:「{}」'
                    '\n硬卧:「{}」\n硬座:「{}」\n无座:「{}」\n\n'.format(
                        train_number, from_station_name, to_station_name,
                        start_time, arrive_time, time_fucked_up,
                        first_class_seat, second_class_seat, soft_sleep,
                        hard_sleep, hard_seat, no_seat))

            # print(info)
            # info_list.append(info)

        return info_list
    except:
        return ' 输出信息有误,请重新输入'
Exemple #17
0
 def send_file_data(self, url, dict=None, file_name=None):
     re = requests.post(url, data=dict, files=file_name)
     print('url:{}\r\nmethod:{}\r\nrequest_data:{}\r\nresponse:{}'.format(
         url, 'post', dict, re.json()))
     return re.json()
Exemple #18
0
import requests as r
import datetime
import re
import matplotlib.pyplot as plt

re = r.get('https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD,EUR,PKR')

content = re.json()

curr = 'USD'

btc = content['BTC'][curr]

wr = str(btc)


date = datetime.datetime.now()

values = []
time = []
n = 0

with open('a.txt', 'a') as fO:
#    fO.write(wr + ' ' + str(date) +  '\n')
    fO.write(wr + ' ' + '\n')

with open('a.txt', 'r') as fO:
    for line in fO:
#        print(line.strip())
        values.append(line.strip())
        n = n+1
Exemple #19
0
import requests
import threading

import re
re = requests.get('http://192.168.43.64:12138')
# 拿到一个response对象
# print(re)

print(re.content.decode('utf8'))
# content是一个二进制结果 可以包括图片 和text区分

print(re.text)  # 拿到的就是一个字符串
print(re.status_code)  # 拿到状态码

print(re.json())  # 将字符串解析成python里面的数据(字典格式(json格式))
def get_pro_dota_games():
    """Live pro dota games
        Parameters
        ----------
        args : None

        Returns
        -------
        List
            String list with useful dota pro games 322
        """
    headers = {'User-Agent': 'Mozilla/5.0'}
    re = requests.get(r'https://api.opendota.com/api/live', headers)
    re2 = requests.get(r'https://api.opendota.com/api/leagues', headers)
    re3 = requests.get(r'https://api.opendota.com/api/heroes', headers)
    games = re.json()
    leagues = re2.json()
    heroes = re3.json()
    live_games = []
    for game in games:
        if game['league_id'] != 0:
            league_name = ''
            spectators = game['spectators']
            radiant_name = ''
            dire_name = ''
            if 'team_name_radiant' not in game:
                radiant_name = 'Radiant'
            else:
                radiant_name = game['team_name_radiant']
            if 'team_name_dire' not in game:
                dire_name = 'Dire'
            else:
                dire_name = game['team_name_dire']
            radiant_score = game['radiant_score']
            dire_score = game['dire_score']
            gold_diference = game['radiant_lead']
            radiant_heroes = []
            dire_heroes = []
            for league in leagues:
                if game['league_id'] == league['leagueid']:
                    league_name = (league['name'])
                    if league['tier'] == 'professional':
                        for player in game['players']:
                            for hero in heroes:
                                hero_name = ''
                                if player['hero_id'] == hero['id']:
                                    for hero in heroes:
                                        if 'team_name' not in player:
                                            pass
                                        elif player['hero_id'] == hero['id']:
                                            hero_name = (
                                                hero['localized_name'])
                                            if player[
                                                    'team_name'] == radiant_name:
                                                radiant_heroes.append(
                                                    hero_name)
                                            else:
                                                dire_heroes.append(hero_name)

                    game_dict = {
                        'league_name': league_name,
                        'spectators': str(spectators),
                        'radiant_name': radiant_name,
                        'dire_name': dire_name,
                        'radiant_heroes': str(radiant_heroes),
                        'dire_heroes': str(dire_heroes),
                        'radiant_score': str(radiant_score),
                        'dire_score': str(dire_score),
                        'gold_difference': str(gold_diference),
                    }
                    message = game_dict['league_name'] + '\n' + game_dict['radiant_name'] + ' vs ' + game_dict[
                        'dire_name'] \
                              + '\n' + game_dict['radiant_score'] + ' - ' + game_dict[
                                  'dire_score'] + '\n' + 'Gold Difference: ' + game_dict['gold_difference'] + '\n' + \
                              game_dict['radiant_name'] + ' Heroes: ' + game_dict['radiant_heroes'] + '\n' + \
                              game_dict['dire_name'] + ' Heroes: ' + game_dict['dire_heroes'] + '\nSpectators: ' + \
                              game_dict['spectators']
                    live_games.append(message)
    return live_games
Exemple #21
0
 def send_request(self, method, url, data=None, header=None):
     re = None
     re_error = {'msg': '请求失败', 'code': '请求失败'}
     re_long_lenth = {'msg': '返回字节超过32767', 'code': '返回字节超过32767'}
     re_type_error = {
         'code': 10001,
         'msg': '返回数据格式不是json,当前框架无法处理,请联系框架开发者--谷哥'
     }
     if method == 'get':
         try:
             re = requests.get(url, headers=header)
         except Exception as e:
             re = False
     elif method == 'post':
         if header['Content-Type'] == 'application/x-www-form-urlencoded':
             try:
                 re = requests.post(url, data=data, headers=header)
             except Exception as e:
                 re = False
         elif header['Content-Type'] == 'text/xml':
             try:
                 re = requests.post(url, json=data, headers=header)
             except Exception as e:
                 re = False
         elif header['Content-Type'] == 'application/json':
             try:
                 re = requests.post(url, json=data, headers=header)
             except Exception as e:
                 re = False
         elif header['Content-Type'] == 'multipart/form-data':
             try:
                 del header['Content-Type']
                 re = requests.post(url, data=data, headers=header)
             except Exception as e:
                 re = False
         else:
             re = False
     elif method == 'delete':
         try:
             re = requests.delete(url, headers=header)
         except Exception as e:
             re = False
     elif method == 'patch':
         try:
             re = requests.patch(url, headers=header)
         except Exception as e:
             re = False
     print('url:{}\r\nmethod:{}\r\nrequest_data:{}'.format(
         url, method, data))
     if re and re.status_code == 200:
         print('response_code: {}'.format(re.status_code))
         if re.headers['Content-Type'] in 'application/json;charset=UTF-8':
             if len(json.dumps(re.json(), ensure_ascii=False)
                    ) < 32767:  # 当单返回数据长度超过32767,xlrd模块处理不了写入
                 print('response:{}'.format(re.json()))
                 return re.json()
             else:
                 return re_long_lenth
         else:
             print('response:{}'.format(re_type_error))
             return re_type_error
     else:
         print('response_code: {}'.format(re.status_code))
         print(
             'url:{}\r\nmethod:{}\r\nrequest_data:{}\r\nresponse:{}'.format(
                 url, method, data, '请求失败'))
         return re_error