예제 #1
0
def spotify_request(method,
                    endpoint,
                    token,
                    expected_code,
                    data=None,
                    json=None,
                    silent=False):
    response = request(method,
                       'https://api.spotify.com/v1/' + endpoint,
                       headers={
                           "Accept": "application/json",
                           "Content-Type": "application/json",
                           "Authorization": "Bearer " + token
                       },
                       data=data,
                       json=json)
    if response.status_code == expected_code:
        return (response, None)

    if not silent:
        sys.stderr.write('something went wrong\n')
        try:
            sys.stderr.write(response.json()['error']['message'] + '\n')
            sys.stderr.write('reason: ' + response.json()['error']['reason'])
        except json.decoder.JSONDecodeError:
            sys.stderr.write('error ' + str(response.status_code) +
                             ' ~ empty body ~')
        except KeyError:
            sys.stderr.write(str(response.json()))
        sys.stderr.write('\n')

    return (response, response.status_code)
예제 #2
0
def kanalaSortu():
    metodoa = 'POST'
    uria = "https://api.thingspeak.com/channels.json"
    goiburuak = {
        'Host': 'api.thingspeak.com',
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    edukia = {
        'api_key': 'YJYOOFOU0YKE2ZI9',
        'name': 'Kanala',
        'field1': "%CPU",
        'field2': "%RAM"
    }

    edukia_encoded = urllib.parse.urlencode(edukia)
    goiburuak['Content-Length'] = str(len(edukia_encoded))
    erantzuna = requests.request(metodoa,
                                 uria,
                                 data=edukia,
                                 headers=goiburuak,
                                 allow_redirects=False)
    edukia = json.loads(erantzuna.content)

    global kanalID
    kanalID = edukia[0]['id']
    kanalAPI = edukia[0]['api_keys'][0]['api_key']

    kodea = erantzuna.status_code
    deskribapena = erantzuna.reason
    print(str(kodea) + " " + deskribapena)
    edukia = erantzuna.content
    print(edukia)

    return kanalID, kanalAPI
예제 #3
0
def notion_request(method,
                   endpoint,
                   token,
                   expected_code=200,
                   data=None,
                   json=None,
                   verbose=False):
    response = request(method,
                       'https://api.notion.com/v1/' + endpoint,
                       headers={
                           "Authorization": "Bearer " + token,
                           "Content-Type": "application/json",
                           "Notion-Version": "2021-08-16",
                       },
                       data=data,
                       json=json)
    if response.status_code == expected_code:
        return response.json()
    print(response)
    if verbose:
        sys.stderr.write('something went wrong\n')
        sys.stderr.write('ERROR ' + str(response.status_code) + '\n')

    #raise (response.json(), response.status_code)
    return None
예제 #4
0
def getRList(request):
    Rname = request.GET['Rname']
    cuisine = request.GET['cuisine']
    rating = request.GET['rating']
    # name=request.GET['name']
    print(Rname, cuisine, rating, " printing details")

    url = "http://127.0.0.1:8000/apii/RestaurantList/"
    payload = {"Rname": Rname, "cuisine": cuisine, "rating": rating}
    payload = json.dumps(payload)
    # payload = "{\r\n    \"email\": \"[email protected]\",\r\n    \"password\": \"suman5\",\r\n    \"name\": \"suman5\"\r\n}"
    headers = {
        'Token': '',
        'X-Amz-Content-Sha256':
        'beaead3198f7da1e70d03ab969765e0821b24fc913697e929e726aeaebf0eba3',
        'X-Amz-Date': '20200702T013306Z',
        'Authorization':
        'AWS4-HMAC-SHA256 Credential=undefined/20200702/us-east-1/execute-api/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=6b2753c6f4ee84dbef9e5b717cc760b2de89fc5bad9d4d5f4d6817a44d20076f',
        'Content-Type': 'application/json'
    }

    response = requests.request("GET", url, headers=headers, data=payload)

    data = response.text
    return render(request, 'temp.html', {'data': data})
예제 #5
0
def index_post():
    print("methods=['POST']")
    category = request.form.get('category')
    image = request.files.get('image')

    if category in ['programming', 'text']:
        req = requests.request(
            method='POST',
            url='http://127.0.0.1:5001/api/save-image/',
            files=dict(
                image=(
                    image.filename,
                    image.stream,
                    image.mimetype
                )
            ),
            data=dict(
                category=category,
                secret=SECRET_KEY
            )
        )

        if req.status_code == requests.codes.ok:
            data = req.json()
            print(data)
예제 #6
0
 def Lat_Lon_Find(input):
     url = "https://us1.locationiq.com/v1/search.php?key=pk.b31969419cb75a4fa46f0419635ee6c3&q=%s&format=json"%(input)
     payload = {}
     headers= {}
     response = requests.request("GET", url, headers=headers, data=payload)
     print(url)
     Lat = json.loads(response.text)[0]['lat']
     Lon = json.loads(response.text)[0]['lon']
     return(Lat,Lon,input)
예제 #7
0
파일: Unit_test.py 프로젝트: Qdo45/test
 def test_file_correct_data_in_file_and_person_True(self):
     url = "http://127.0.0.1:5000/openfile"
     payload = {'person': 'True'}
     files = [('file', ('33.xml', open('33.xml', 'rb'), 'text/xml'))]
     headers = {}
     response = requests.request("GET",
                                 url,
                                 headers=headers,
                                 data=payload,
                                 files=files)
     assert response.status_code == 200
     files[0][1][1].close()
예제 #8
0
 def aqi(result):
     #adding waqi api
     url_value = "https://api.waqi.info/feed/%s/?token=4a10769fcaf1c9b08c25a271fd1c92b1ab1b1db0"%(result[2])
     print(url_value)
     payload = {}
     headers= {}
     response = requests.request("GET",url_value, headers=headers, data = payload)
     print(response) 
     Status_two = json.loads(response.text)["status"]
     print(Status_two)   
     
     if(Status_two == "ok"):
         waqi_output = json.loads(response.text)["data"]
         aqi=waqi_output["aqi"]
         print(aqi)  
         news(country)
     elif(Status_two == "error"):  
         #airpollution api
         url_value = "http://api.airpollutionapi.com/1.0/aqi?lat=%s&lon=%s&APPID=lkoc3osdik3gc8u9hg67u0i4ni"%(result[0],result[1])
         print(url_value)
         payload = {}
         headers= {}
         response = requests.request("GET",url_value, headers=headers, data = payload)
         print(response)
         Status = json.loads(response.text)["status"]
         if(Status == "success"):
             Output = json.loads(response.text)["data"]
             print("if condition worked")
             alert = Output["value"]
             country = Output["country"]
             print()
             news(country)
             print(country)
             print(alert)
         
     else:
         print("Inside the block")
예제 #9
0
def send_to_ysz(mat, url):
    data = ""
    for row in mat:
        data += " ".join([str(num) for num in row])
        data += "\n"
    payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"Coefficients\"\r\n\r\n%s\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"outputFormat\"\r\n\r\nfloat\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"outputPrecision\"\r\n\r\n4\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--" % (
        data)
    headers = {
        'content-type':
        "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
        'cache-control': "no-cache",
        'postman-token': "575258bf-5724-7191-9537-5d92fff0370d"
    }
    response = requests.request("POST", url, data=payload, headers=headers)
    return response.text
예제 #10
0
def datuIgoera(kanalAPI):
    metodoa = 'GET'
    uria = "https://api.thingspeak.com/update.json"
    goiburuak = {'Host': 'api.thingspeak.com'}
    edukia = {'api_key': kanalAPI, 'field1': cpu(), 'field2': ram()}
    erantzuna = requests.request(metodoa,
                                 uria,
                                 data=edukia,
                                 headers=goiburuak,
                                 allow_redirects=False)
    kodea = erantzuna.status_code
    deskribapena = erantzuna.reason
    print(str(kodea) + " " + deskribapena)
    edukia = erantzuna.content
    print(edukia)
예제 #11
0
def kanalaHustu(kanalID):

    metodoa = 'DELETE'
    uria = "https://api.thingspeak.com/channels/" + str(
        kanalID) + "/feeds.json"
    goiburuak = {'Host': 'api.thingspeak.com'}
    edukia = {'api_key': 'YJYOOFOU0YKE2ZI9'}
    erantzuna = requests.request(metodoa,
                                 uria,
                                 data=edukia,
                                 headers=goiburuak,
                                 allow_redirects=False)
    kodea = erantzuna.status_code
    deskribapena = erantzuna.reason
    print(str(kodea) + " " + deskribapena)
    edukia = erantzuna.content
    print(edukia)
예제 #12
0
파일: app.py 프로젝트: treetree0211/cmpe285
def current_result():
    if request.method == 'POST':
        ticker = request.form['Ticker Symbol']
        now = datetime.now(pytz.timezone('US/Pacific'))
        time = now.strftime("%m/%d/%Y, %H:%M:%S")
        url = "https://apidojo-yahoo-finance-v1.p.rapidapi.com/market/get-quotes"
        querystring = {"region": "US", "lang": "en", "symbols": ticker}
        headers = {
            'x-rapidapi-host': "apidojo-yahoo-finance-v1.p.rapidapi.com",
            'x-rapidapi-key': "x-rapidapi-key"
        }

        response = requests.request("GET",
                                    url,
                                    headers=headers,
                                    params=querystring)
        data = response.json()
        result = data['quoteResponse']['result']

        if len(result) == 0:
            name = "Invalid Ticker"
            price = ""
            value_change = ""
            percent_change = ""
        else:
            name = result[0]['longName']
            price = '{:,.2f}'.format(result[0]['regularMarketPrice'])
            v_change = float(result[0]['regularMarketChange'])
            p_change = float(result[0]['regularMarketChangePercent'])

            if v_change > 0:
                value_change = "+" + '{:,.2f}'.format(v_change)
            else:
                value_change = '{:,.2f}'.format(v_change)

            if p_change > 0:
                percent_change = "+" + '{:,.2f}'.format(p_change) + "%"
            else:
                percent_change = '{:,.2f}'.format(p_change) + "%"

    return render_template('res.html',
                           time=time,
                           name=name,
                           price=price,
                           value_change=value_change,
                           percent_change=percent_change)
예제 #13
0
def fore_cast():
    url = "https://api.waqi.info/feed/bangalore/?token=4a10769fcaf1c9b08c25a271fd1c92b1ab1b1db0"
    payload = {}
    headers = {}
    response = requests.request("GET", url, headers=headers, data=payload)
    #print(json.loads(response.text)["records"])
    result1 = []
    result2 = []
    result3 = []
    result4 = []
    result1 = json.loads(response.text)["data"]["forecast"]["daily"]["o3"]
    result2 = json.loads(response.text)["data"]["forecast"]["daily"]["pm10"]
    result3 = json.loads(response.text)["data"]["forecast"]["daily"]["pm25"]
    result4 = json.loads(response.text)["data"]["forecast"]["daily"]["uvi"]
    #print(result)
    day = []
    o3_values = []
    for value in result1:
        o3_values.append(value["avg"])
        day.append(value["day"])
    
    pm10_values = []
    for value in result2:
        pm10_values.append(value["avg"])
    
    pm25_values = []
    for value in result3:
        pm25_values.append(value["avg"])
    
    uvi_values = []
    for value in result4:
        uvi_values.append(value["avg"])
    
    final_data = {}
    final_data["o3_values"] = o3_values
    final_data["pm10_values"] = pm10_values
    final_data["pm25_values"] = pm25_values
    final_data["uvi_values"] = uvi_values
    final_data["day"] = day

    print(final_data)


    #print(result)
    return final_data
예제 #14
0
def frontPage():
    lat= request.args.get('lat')   
    lon = request.args.get('long')
    print("...............................")
    print(lat)
    print(lon)
    def find_location(lat,lon):
        print(lat)
        print(lon)
        lat = str(float(lat) + 5.3982)
        lon = str(float(lon) - 2.4279)
        print(lon)
        api_url = "https://us1.locationiq.com/v1/reverse.php?key=pk.b31969419cb75a4fa46f0419635ee6c3&format=json&lat=34.038303&lon=74.819557"
        payload = {}
        headers= {}
        response = requests.request("GET", api_url, headers=headers, data = payload)
        address = json.loads(response.text)
        city = address["address"]["county"]
        state =  address["address"]["state"]
        country = address["address"]["country"]
        if(state == "Jammu and Kashmir"):
            city ="Srinagar"
        print(city)
        return(city,state,country)
    city_state_country = find_location(lat,lon)
  
    
    url_value = "http://api.airvisual.com/v2/city?city=%s&state=%s&country=%s&key=ed06533f-c5d9-4b3e-8605-6d3c4c716970"%(city_state_country[0],city_state_country[1],city_state_country[2])
    print(url_value)
    payload = {}
    headers= {}
    response = requests.request("GET",url_value, headers=headers, data = payload)
    print(response)
    Status = json.loads(response.text)["status"]
    print(Status)
    api_output = json.loads(response.text)["data"]
   
    api_output['placeName']=api_output["city"]
    api_output['state'] = api_output['state']
    api_output['country']= api_output['country']
    api_output['aqiusa']= api_output['current']['pollution']['aqius']
    api_output['aqichina']= api_output['current']['pollution']['aqicn']
    api_output['temperature']= api_output['current']['weather']['tp']
    api_output['humidity']= api_output['current']['weather']['hu']
    return api_output    
예제 #15
0
파일: Unit_test.py 프로젝트: Qdo45/test
 def test_path_incorrect(self):
     url = "http://127.0.0.1:5000/op3enfile"
     payload = {
         'person': 'False',
         'start_date': '01-01-2020',
         'end_date': '01-01-1990'
     }
     files = [('file', ('', open('33.xml', 'rb'), 'text/xml'))]
     headers = {}
     response = requests.request("GET",
                                 url,
                                 headers=headers,
                                 data=payload,
                                 files=files)
     assert response.status_code == 404
     self.assertRegex(response.text.encode().decode('unicode_escape'),
                      "Дата начала больше даты окончания")
     files[0][1][1].close()
예제 #16
0
파일: Unit_test.py 프로젝트: Qdo45/test
 def test_file_incorrect(self):
     url = "http://127.0.0.1:5000/openfile"
     payload = {
         'person': 'False',
         'start_date': '01-01-2020',
         'end_date': '01-01-2020'
     }
     files = [('file', ('', open('33.xml', 'rb'), 'text/xml'))]
     headers = {}
     response = requests.request("GET",
                                 url,
                                 headers=headers,
                                 data=payload,
                                 files=files)
     assert response.status_code == 200
     self.assertRegex(response.text.encode().decode('unicode_escape'),
                      "Файл не найден")
     files[0][1][1].close()
 def SendOut(self, url=None, payload=None, headers=None):
     try:
         response = requests.request("GET", url, headers=headers)
         # 如果返回状态码不是200,抛出异常
         response.raise_for_status()
         # 返回结果转json格式赋值给变量r
         self.r = response.json()
         # 判断!如果返回状态不是Ok并且错误内容是系统内部错误,返回错误信息
         if 'result' in self.r:
             pass
         elif 'reason' in self.r:
             print("下面是接口返回:\n%s" % self.r)
         else:
             print("下面是接口返回:\n%s" % self.r)
         return self.r
     # 捕获json格式错误异常,response状态码不为200的异常
     except (json.decoder.JSONDecodeError, requests.RequestException) as e:
         print(e)
예제 #18
0
 def find_location(lat,lon):
     print(lat)
     print(lon)
     lat = str(float(lat) + 5.3982)
     lon = str(float(lon) - 2.4279)
     print(lon)
     api_url = "https://us1.locationiq.com/v1/reverse.php?key=pk.b31969419cb75a4fa46f0419635ee6c3&format=json&lat=34.038303&lon=74.819557"
     payload = {}
     headers= {}
     response = requests.request("GET", api_url, headers=headers, data = payload)
     address = json.loads(response.text)
     city = address["address"]["county"]
     state =  address["address"]["state"]
     country = address["address"]["country"]
     if(state == "Jammu and Kashmir"):
         city ="Srinagar"
     print(city)
     return(city,state,country)
 def test_b_add(self):
     '''文档上传成功'''
     global ADDURL
     files = {'file': open('F:/MyqWork/test.docx', 'rb')}
     response = requests.request("POST",ADDURL,files=files)
     files.clear()
     r = response.json()
     if r == None:
         print('请求失败,没有返回数据')
         self.assertEqual(None,'')
         return
     print("请求url:%s" % ADDURL)
     print("上传文档操作:")
     print("返回数据: %s" % r)
     self.assertEqual(r['errorCode'],0)
     docId = r['datas']['docId']
     try:
         self.with_docId.withWriteDocId(docId)
     except Exception as e:
         print(e)
예제 #20
0
def kanalaSortutaAlaEz():
    metodoa = 'GET'
    uria = "https://api.thingspeak.com/channels.json"
    goiburuak = {'Host': 'api.thingspeak.com'}
    edukia = {'api_key': 'YJYOOFOU0YKE2ZI9'}

    erantzuna = requests.request(metodoa,
                                 uria,
                                 data=edukia,
                                 headers=goiburuak,
                                 allow_redirects=False)
    edukia = json.loads(erantzuna.content)

    if (len(edukia) > 0):
        emaitza = True
        kanalID = edukia[0]['id']
        kanalAPI = edukia[0]['api_keys'][0]['api_key']
    else:
        emaitza = False

    return emaitza, kanalID, kanalAPI
예제 #21
0
def testData():

    url = "https://api.data.gov.in/resource/3b01bcb8-0b14-4abf-b6f2-c1bfd384ba69?api-key=579b464db66ec23bdd0000019a6ac6e8d7cc45ff6fa12518db0ddd77&format=json&offset=0&limit=1600"
    payload = {}
    headers = {}
    response = requests.request("GET", url, headers=headers, data=payload)
   
    result = []
    result = json.loads(response.text)["records"]

    cities = []
    aqi_values = []
    NO2_values = []
    CO_values = []
    SO2_values = []

    for value in result:
        if (value["city"] not in cities):
                cities.append(value["city"])
        if value["pollutant_id"] == "PM2.5":
                aqi_values.append(value["pollutant_avg"])
        if value["pollutant_id"] == "NO2":
                NO2_values.append(value["pollutant_avg"]) 
        if value["pollutant_id"] == "SO2":
                SO2_values.append(value["pollutant_avg"])
        if value["pollutant_id"] == "CO":
                CO_values.append(value["pollutant_avg"])        
        

    final_data = {}
    final_data["cities"] = cities
    final_data["aqi_values"] = aqi_values
    final_data["NO2_values"] = NO2_values
    final_data["SO2_values"] = SO2_values
    final_data["CO_values"] = CO_values

    
    
    return final_data
예제 #22
0
def submitUser(request):
    email = request.GET['email']
    password = request.GET['password']
    name = request.GET['name']
    print(email, password, name, " printing details")

    url = "http://127.0.0.1:8000/apii/login/"
    payload = {"email": email, "password": password, "name": name}
    payload = json.dumps(payload)
    # payload = "{\r\n    \"email\": \"[email protected]\",\r\n    \"password\": \"suman5\",\r\n    \"name\": \"suman5\"\r\n}"
    headers = {
        'Token': '',
        'X-Amz-Content-Sha256':
        'beaead3198f7da1e70d03ab969765e0821b24fc913697e929e726aeaebf0eba3',
        'X-Amz-Date': '20200702T013306Z',
        'Authorization':
        'AWS4-HMAC-SHA256 Credential=undefined/20200702/us-east-1/execute-api/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=6b2753c6f4ee84dbef9e5b717cc760b2de89fc5bad9d4d5f4d6817a44d20076f',
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    data = response.text
    return render(request, 'login.html', {'data': data})
예제 #23
0
from pip._vendor import requests

U = "https://ccapi.csslcloud.net/api/room/link?roomid=41EEFCE481E030309C33DC5901307461&userid=6634678BEDA5BB7D&time=1539831085&hash=a8e8b8c06e82d9c2ef7f94e4b070a00e====提交数据:roomid=41EEFCE481E030309C33DC5901307461&userid=6634678BEDA5BB7D&time=1539831085&hash=a8e8b8c06e82d9c2ef7f94e4b070a00e "
url = "https://document.csslcloud.net/api/document/upload?userid=83F203DAC2468694&docid=1FE5491B7EAA3A599C33DC5901307461"

files = {'file': open('F:/MyqWork/test.docx', 'rb')}
headers = {
    'content-type':
    "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
    'Cache-Control': "no-cache",
    'Postman-Token': "a33c9ef5-55f1-4e92-93ba-f765bd08a62b"
}

response = requests.request("POST", url, files=files)

print(response.text)
예제 #24
0
def searchT():
    if request.method == 'POST':      
        city = request.form.get('city')
        print("City Found Inside Request Method---------=:- "+ city)
        city = city.title()
        #Comparsion city and state
        def stateName(city):
            print("The Name of city Inside State Name fuction-------=:- "+ city)
            flag ='N'
            for data in courseData:
                if data["city"]== city:
                    flag = 'Y'
                    break
            #return data["state"]    
            if flag =='Y':
                return data["state","country"]
            else:
                return 'No data Found'
        
        # return render_template("Result.html")
        # city = 'srinagar'
        state = stateName(city)        
        url = "http://api.airvisual.com/v2/city?city=%s&state=%s&country=%scountry&key=ed06533f-c5d9-4b3e-8605-6d3c4c716970" %(city,state,country)   
        payload = {}
        headers= {}
        response = requests.request("GET", url, headers=headers, data = payload)
        print(url)
        print(json.loads(response.text))
        airResponse = json.loads(response.text)["data"]
 
        qualityValue=airResponse["current"]["pollution"]["aqius"]
        # message_window=None
        # message=None
        # message_window=Nones
        # message_outdoor=None
        

        if(qualityValue<50):
            quality="Good"
            message="Wear a mask outdoors"
        elif(qualityValue>=51 and qualityValue<99):
            quality="Satisfactory"
            purifier="	Run an air purifier"   
            message="Wear a mask outdoors"
            message_outdoor="Avoid Outdoor Excercise" 
            message_window="Close your windows to avoid dirty outdoor air"
        elif(qualityValue>100 and qualityValue<=200):
            quality="Unhealthy For Sensitive Groups"
            purifier="	Run an air purifier"   
            message="Wear a mask outdoors"
            message_window="Close your windows to avoid dirty outdoor air"
            message_outdoor="Avoid Outdoor Games"
        elif(qualityValue>200 and qualityValue<=300):
            quality="Unhealthy"
        elif(qualityValue>301 and qualityValue<=400):
            quality="Very Poor"
        else:
            quality="Severe"

        #for weather priction
        weather_icon =  airResponse["current"]["weather"]["ic"]
        print(weather_icon)
        if(weather_icon =="06n"):
            output = "Clear Sky"
        elif(weather_icon == "01n"):
            output = "Clear Sky(night)"
        elif(weather_icon == "02d"):
            output = "few Clouds(day)"
        elif(weather_icon == "02n"):
            output = "few clouds"
        elif(weather_icon == "03d"):
            output = "scattered cloud"
        elif(weather_icon == "04d"):
            output = "Broekn cloud"
        elif(weather_icon == "09d"):
            output = "shoer rain"
        elif(weather_icon == "04n"):
            output = "Rainday time"
        else:
            output = "Rain Night time"


        #return render_template("enrollment.html", enrollment=True, data={"id":id, "title":title, "term":term ,"location":airResponse["city"], "pollution":airResponse["current"]["pollution"]["aqius"],"quality":quality})
        # return render_template("result.html", enrollment=True, data={"id":id, "title":title, "term":term ,"location":airResponse["city"], "pollution":airResponse["current"]["pollution"]["aqius"],"weather":airResponse["current"]["weather"]["tp"],"Humidity":airResponse["current"]["weather"]["hu"],"pressure":airResponse["current"]["weather"]["pr"],"windspeed":airResponse["current"]["weather"]["ws"],"quality":quality,"message":message,"message_window":message_window,"message_outdoor":message_outdoor})
        data = {}
        data['city']=airResponse['city']
        data['state']=airResponse['state']
        data['pollution']=airResponse["current"]["pollution"]["aqius"]
        print(qualityValue)
        data['value']=qualityValue
        data['message']=message_window
        data['quality']= quality 
        data['purifier']=purifier
        data['messageOutdoor'] =message_outdoor
        data['messageWindow']=message_window
        #WEATHER VARIABLE
        data['temperature']=airResponse["current"]["weather"]["tp"]
        data['pressure']=airResponse["current"]["weather"]["pr"]
        data['humidity'] = airResponse["current"]["weather"]["hu"]
        data['windspeed']=airResponse["current"]["weather"]["ws"]
        data['wind_direction']=airResponse["current"]["weather"]["wd"]
        data['icon']=output
        print(data)    
        
        return render_template("test.html",data=data)
예제 #25
0
def search_location():
    message_window=None
    message=None
    message_window=None
    message_outdoor=None
   
    worst_cities = newsapi.get_top_cities()
    best_cities = newsapi.get_bottom_cities()
    resultant={}
    
    if request.method == 'POST':
        city_data=None
        state = None
        country = None
        input = request.form.get('city')
        input= input.title()
        for data in courseData:
        
            if data["city"]== input:
                
                city_data=data["city"]
                state=data["state"]
                country= data["country"]
                break
        
        print(city_data)
        if(city_data != None and state!=None and country !=None):        
            url_value = "http://api.airvisual.com/v2/city?city=%s&state=%s&country=%s&key=ed06533f-c5d9-4b3e-8605-6d3c4c716970"%(city_data,state,country)
            print(url_value)
            payload = {}
            headers= {}
            response = requests.request("GET",url_value, headers=headers, data = payload)
            print(response)
            api_output = json.loads(response.text)["data"]         
            print(api_output)
            print(api_output["city"])
            city=api_output["city"] 
            state= api_output['state']
            country= api_output['country']
            aquius= api_output['current']['pollution']['aqius']
            aqichina= api_output['current']['pollution']['aqicn']
            temperature= api_output['current']['weather']['tp']
            humidity= api_output['current']['weather']['hu']
            qualityValue = api_output['current']['pollution']['aqius']
            
            #checking Condition
            if(qualityValue<50):
                quality="Good"
                message="Wear a mask outdoors"  
            elif(qualityValue>=51 and qualityValue<99):
                quality="Satisfactory"
                message="Wear a mask outdoors"
                message_outdoor="Avoid Outdoor Excercise" 
                message_window="Close your windows to avoid dirty outdoor air"
            elif(qualityValue>100 and qualityValue<=200):
                quality="Unhealthy For Sensitive Groups"
                message="Wear a mask outdoors"
                message_window="Close your windows to avoid dirty outdoor air"
                message_outdoor="Avoid Outdoor Games"
            elif(qualityValue>200 and qualityValue<=300):
                quality="Unhealthy"
            elif(qualityValue>301 and qualityValue<=400):
                quality="Very Poor"
            else:
                quality="Severe"
                        
            
            combined_Data={}
            combined_Data['city']=city
            combined_Data['state']=state
            combined_Data['aquius']=aquius
            combined_Data['aqichina']=aqichina
            combined_Data['temperature']=temperature
            combined_Data['humidity']=humidity
            combined_Data['city']=city
            combined_Data['message']=message
            combined_Data['message_window']=message_window
            combined_Data['message_outdoor']=message_outdoor
            combined_Data['quality']=quality
             
            return render_template("search_location.html",data=combined_Data,worst_cities_=worst_cities,best_cities_=best_cities)
        else:
            print("no data")
        
       
    
        
    return render_template("search_location.html",data=None,worst_cities_=worst_cities,best_cities_=best_cities)     
with open('../data/roomId_list.txt', 'r', encoding='utf-8') as f:
    roomid_list = f.readlines()

# def roomid_l():
#     for i in roomid_list:
#         return (i.strip('\n'))

for i in roomid_list:
    live_roomid = i.strip('\n')
    role1_data = {
        "name": "testauto",
        "userid": USERID,
        "roomid": live_roomid,
        "password": "******",
        "role": '0',
        "client": '0'
    }
    role1_data = t.get_thqs(role1_data)
    role1_url = url + role1_data

    response = requests.request("GET", role1_url)
    r = response.json()
    print(r)
    sessionid = r['data']['sessionid']
    with open('../data/sessionid_list31.txt',
              'a',
              newline='\n',
              encoding='utf-8') as f:
        f.write(sessionid + '\n')
    time.sleep(0.8)