def getUserImage(filename): authResponse = authentication() try: small = request.args.get('small', default=1, type=int) if authResponse["statusCode"] == 200 and authResponse["isVerified"]: if small == 1: readFolderPath = os.getenv('CACHE_FOLDER') else: readFolderPath = app.config['UPLOAD_FOLDER'] return send_from_directory( os.path.join(os.getcwd(), readFolderPath), filename) return app.response_class( response=json.dumps({ "status": "unauthorized", "error": authResponse.get("error") }), mimetype="application/json"), authResponse.get("statusCode") except Exception as e: return app.response_class(response=json.dumps({ "status": "failure", "error": e.__str__() }), mimetype="application/json"), 400
def main(): videoId = input('Enter videoId:') categoryId = input('Enter categoryId:') youtube = auth.authentication() x = videostats( youtube, videoId )[0] # YOU CAN PUT A LOOP HERE TO CONTINOUSLY CHECK THE VIEWS AND CHANGE THE TITLE update( youtube, videoId, x, categoryId ) #BUT THERE IS A QUOTA LIMIT SET BY GOOGLEFOR YOUR PROJECT TO ACCESS THEIR API .
def sendEmail(): authResponse = authentication() if authResponse["statusCode"] == 200 and authResponse["isVerified"]: userId = authResponse.get("data").get("user_id") emailRes = getEmail(userId) if not emailRes.get("status"): return app.response_class( response=json.dumps({ "status": "failure", "error": emailRes.get("error"), "msg": None }), mimetype="application/json", ), 400 if emailRes.get("data").get("email_verified"): return app.response_class( response=json.dumps({ "status": "failure", "error": None, "msg": "Email already verified" }), mimetype="application/json", ), 200 email = emailRes.get("data").get("email") emailToken = serializer.dumps(email, salt='auth-server-email-verification') link = url_for("verifyEmail", token=emailToken, _external=True) mail.send( Message(subject="LenDen-Confirm Email", recipients=[email], html=render_template( "verificationMailTemplate.html", link=link, ))) return app.response_class( response=json.dumps({ "status": "success", "error": None, "msg": f'Verifcation mail sent to {email}' }), mimetype="application/json", ), 200 return app.response_class( response=json.dumps({ "status": "unauthorized", "error": authResponse.get("error") }), mimetype="application/json", ), 401
def login(): if request.method == "POST": username = request.form.get("username") password = request.form.get("password") if auth.authentication(username, password, db): return redirect(url_for("search")) else: return render_template("login.html", error="Bad username or password.") else: return render_template("login.html")
def user_auth(self, data): username = data.get("username") password = data.get("password") auth_status, auth_msg = auth.authentication(username, password) if auth_status is True: print "auth succesful", auth_msg response_data = {"status": "200", "data": []} self.login_user = username self.home_path = "%s\%s" % (settings.USER_BASE_HOME_PATH, username) else: print "auth failed....", auth_msg response_data = {"status": "201", "data": []} self.request.send(json.dumps(response_data))
def user_auth(self, data): username = data.get("username") password = data.get("password") print "===>got here...", username, password auth_status, auth_msg = authentication(username, password) if auth_status is True: print "authentication successful ..." response_data = {'status': '200', 'data': []} self.login_user = username #加个类变量,用以验证是这个用户登录成功了 self.home_path = "%s/%s" % (settings.USER_BASE_HOME_PATH, self.login_user) else: print "authentication failed ..." response_data = {'status': '201', 'data': []} self.request.send(json.dumps(response_data)) #发给客户端相关状态码
def __init__(self, config, logname='imagemngr'): """ Create an instance of the image manager. """ logformat='%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' self.logger = logging.getLogger(logname) ch = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s [%(name)s] %(levelname)s : %(message)s') ch.setFormatter(formatter) ch.setLevel(logging.DEBUG) self.logger.addHandler(ch) self.logger.debug('Initializing image manager') self.config=config if 'Platforms' not in self.config: raise NameError('Platforms not defined') self.systems=[] self.tasks=[] self.expire_requests=dict() self.task_image_id=dict() # TIme before another pull can be attempted self.pullupdatetimeout=300 if 'PullUpdateTime' in self.config: self.pullupdatetimeout=self.config['PullUpdateTimeout'] # Max amount of time to allow for a pull self.pulltimeout=self.pullupdatetimeout*10 # This is not intended to provide security, but just # provide a basic check that a session object is correct self.magic='imagemngrmagic' if 'Authentication' not in self.config: self.config['Authentication']="munge" self.auth=auth.authentication(self.config) self.platforms=self.config['Platforms'] for system in self.config['Platforms']: self.systems.append(system) # Connect to database if 'MongoDBURI' in self.config: client = MongoClient(self.config['MongoDBURI']) db=self.config['MongoDB'] self.images=client[db].images else: raise NameError('MongoDBURI not defined') initqueue(config)
def user(): authResponse = authentication() if authResponse["statusCode"] == 200 and authResponse["isVerified"]: userId = authResponse.get("data").get("user_id") userDataRes = getUser(userId) if not userDataRes.get("status"): return app.response_class(response=json.dumps({ "status": "failure", "error": userDataRes.get("error"), }), mimetype="application/json"), 400 userData = userDataRes.get("data") userData.update({ "access_token": request.headers.get("Authorization").split(" ")[1], "token_type": "JWT", "expires_in": JWT_LIFE_SPAN, }) return app.response_class( response=json.dumps( { "status": "success", "error": None, "data": userData, }, default=json_util.default), mimetype="application/json"), authResponse["statusCode"] return app.response_class( response=json.dumps( { "status": "unauthorized", "data": None, "error": authResponse["error"] }, default=json_util.default), mimetype="application/json"), authResponse["statusCode"]
def user_auth(self,data): #用户验证方法,方法名必须是服务端和客户端商议好的名称。 #用户验证方法 这里的账户信息即可以支持文件有可以支持数据库,两者的存取方式不同 #在这里可以要处理多种情况,因此不要在这里写如何读取用户名和密码 username = data.get("username") password = data.get("password") auth_mag,auth_status = auth.authentication(username,password) #把信息交给认证模块去验证,返回的是结果信息和True或False if auth_status is True: #如果返回status是True 则成功,否则失败 #在服务器端认证成功,那么客户端在发送数据时就不需要再次认证了。 w = settings.USER_BASE_HOME_PATH b = username.encode(encoding='utf-8') #这里很坑爹!! self.home_path = "%s%s\\" % (w,b) #获得用户的家目录,以便传文件 self.login_user = username #设置一个变量,确认客户端已经验证通过,以后无需验证 print "Auth Successful....................",auth_mag response_data = {'status':'200',"data":[]} else: print "Auth faild...............!!!!!!!!!",auth_mag response_data = {'status':'201',"data":[]} self.request.send(json.dumps(response_data)) #向客户端发送认证的结果
def user_auth(self, data): username = data.get("username") password = data.get("password") print("====>got here...", username, password) auth_status, auth_msg = auth.authentication(username, password) if auth_status is True: print "Authentication Success ...", auth_msg response_data = { "status": "200", "data": [] } self.login_user.append(username) self.home_path = "%s/%s" % (setting.USER_BASE_HOME_PATH, username) else: print "Authentication Failed ....", auth_msg response_data = { "status": "201", "data": [] } self.request.send(json.dumps(response_data))
def verifyToken(): authResponse = authentication() if authResponse["statusCode"] == 200 and authResponse["isVerified"]: return app.response_class(response=json.dumps({ "status": "success", "error": None }), mimetype="application/json"), 200 if authResponse["statusCode"] == 400 and not authResponse["isVerified"]: return app.response_class(response=json.dumps({ "status": "failure", "error": authResponse.get("error") }), mimetype="application/json"), 400 return app.response_class( response=json.dumps({ "status": "unauthorized", "error": authResponse.get("error") }), mimetype="application/json"), authResponse.get("statusCode")
avg_temp_by_date[k] = np.mean(temp_by_date[k]) avg_temp = np.mean(list(avg_temp_by_date.values())) print(f'Average temperature last 7 days: {np.round(avg_temp, 0):.0f} degree(s) C') temp_plot(avg_temp_by_date) return avg_temp print(f'Getting data from {datetime.datetime.fromtimestamp(int(date_begin))} to {datetime.datetime.fromtimestamp(int(date_end))}') credentials = None token = dict() if len(sys.argv) == 1: credentials = auth.get_input() else: credentials = auth.get_input(sys.argv[1]) err = 0 try: token[token_properties[0]], token[token_properties[1]], token[token_properties[2]] = auth.authentication(credentials) err = 1 set_API(token[token_properties[0]]) data_req = requests.get(base_url, headers=headers, params=parameters).json() calculate(data_req) except: if err == 0: print('Failed to get access token!') else: print('Failed to retrieve the data!')
return motivasi, nKalimat, nNama except tweepy.TweepError as e: print(e) def mentionTimeline(keywords, since_id, logger): api = tweepy.API(auth) logger.info("Retrieving mentions") new_since_id = since_id for tweet in tweepy.Cursor(api.mentions_timeline, since_id=since_id).items(): new_since_id = max(tweet.id, new_since_id) if tweet.in_reply_to_status_id is not None: continue if any(keyword in tweet.text.lower() for keyword in keywords): motivasi = generateKalimat(kalimat_mention)[0] print( "-----------------------------------------------------------------------" ) logger.info(f"Anwering to {tweet.user.name}") motivasi = motivasi.replace("{nama}", tweet.user.name) print(motivasi) api.update_status(status=motivasi, in_reply_to_status_id=tweet.id, auto_populate_reply_metadata=True) return new_since_id auth = authentication()
import auth import datetime import json import requests uri = "/api/provisioning/get-packages" start_date = end_date = datetime. r = requests.post( url=auth.base_url + uri, headers={"Authorization": auth.authentication(uri), "x-mc-app-id": auth.app_id, "x-mc-date": auth.hdr_date, "x-mc-req-id": auth.request_id, "Content-Type": "application/json"}, data=str({ "data": [ { "admin": "true", "start": "2015-11-16T14:49:18+0000", "searchBy": [ { "fieldName": "String", "value": "String" } ], "end": "2015-11-16T14:49:18+0000", "filterBy": [ { "fieldName": "String",
import auth import json import requests uri = "/api/user/get-profile" r = requests.post(url=auth.base_url + uri, headers={ "Authorization": auth.authentication(uri), "x-mc-app-id": auth.app_id, "x-mc-date": auth.hdr_date, "x-mc-req-id": auth.request_id, "Content-Type": "application/json" }, data=str({ "data": [{ "emailAddress": "*****@*****.**", "showAvatar": False }] })) mc_response = json.loads(r.content) print(f"HTTP Response Body:\n{json.dumps(mc_response, indent=2)}")
and 'true' in crw_full_dct[crw['staffId']]['enabled'])] crw_lst = [crw for crw in crw_lst if crw['position'] in ('FA', 'CM')] return crw_lst cur_date = datetime.now() dates = [datetime.strftime(cur_date + timedelta(days=d), '%Y-%m-%d') for d in range(-3,0)] os.environ['url_main'] = 'https://admin-su.crewplatform.aero/' url_fl_list = 'core/ajax/filter/flights/{{id}}/{{date}}/{{airport}}?draw=4&columns[0][data]=flightNumber&columns[0][name]=flightNumber&columns[0][searchable]=true&columns[0][orderable]=true&columns[0][search][value]={}&columns[0][search][regex]=false&columns[1][data]=departureAirport&columns[1][name]=departureAirport&columns[1][searchable]=true&columns[1][orderable]=true&columns[1][search][value]=&columns[1][search][regex]=false&columns[2][data]=departureDate&columns[2][name]=departureDate&columns[2][searchable]=true&columns[2][orderable]=true&columns[2][search][value]={}&columns[2][search][regex]=false&columns[3][data]=flightStatusLabel&columns[3][name]=flightStatusLabel&columns[3][searchable]=true&columns[3][orderable]=true&columns[3][search][value]=&columns[3][search][regex]=false&columns[4][data]=arrivalAirport&columns[4][name]=arrivalAirport&columns[4][searchable]=true&columns[4][orderable]=true&columns[4][search][value]=&columns[4][search][regex]=false&columns[5][data]=details&columns[5][name]=details&columns[5][searchable]=false&columns[5][orderable]=false&columns[5][search][value]=&columns[5][search][regex]=false&order[0][column]=2&order[0][dir]=desc&start=0&length=20&search[value]=&search[regex]=false&_=1548233858313' url_fl_crw = 'core/flight/details/crew/{}?draw=1&columns[0][data]=staffId&columns[0][name]=staffId&columns[0][searchable]=true&columns[0][orderable]=true&columns[0][search][value]=&columns[0][search][regex]=false&columns[1][data]=name&columns[1][name]=name&columns[1][searchable]=true&columns[1][orderable]=true&columns[1][search][value]=&columns[1][search][regex]=false&columns[2][data]=position&columns[2][name]=position&columns[2][searchable]=true&columns[2][orderable]=true&columns[2][search][value]=&columns[2][search][regex]=false&columns[3][data]=email&columns[3][name]=email&columns[3][searchable]=true&columns[3][orderable]=true&columns[3][search][value]=&columns[3][search][regex]=false&order[0][column]=2&order[0][dir]=asc&start=0&length=20&search[value]=&search[regex]=false&_=1548240002914' txt = open('training_flights_' + datetime.strftime(cur_date, '%Y_%m_%d') + '.txt', 'w') session = auth.authentication()[0] crw_full_lst = get_crw_full_dct() for flight in flights: for date in dates: fl_id, arr_aprt = get_fl_id(flight, date) if fl_id is None: continue crw_lst = get_fl_crw(fl_id) crw_lst = crw_lst_comp(crw_lst, crw_full_lst) txt.write('SU' + flight + ' ' + arr_aprt + ' ' + date + '\n') for crw in crw_lst: txt.write(crw['position'] + ' ' + crw['staffId'] + ' ' + crw['name'] + '\n') txt.write('\n') txt.close()
cursor.execute( "select user_id_md5 from errortable where user_id_md5 = '" + user_id_md5 + "';") summary = cursor.fetchall() error_retry = len(summary) + 1 if error_retry > 5: msg = '<p style="color: red;font-weight: bold;">5回以上パスワードの入力に失敗しましたのでロックしました</p>' sys.stderr.write("Login Error :" + user_id + " / " + str(error_retry) + " more attempts.") sql = "update usertable set lock=1 where md5(user_id)='" + user_id_md5 + "';" cursor.execute(sql) connector.commit() else: user = auth.authentication(user_id, passwd) if user is None: sys.stderr.write("Login Error :" + user_id + " / " + str(error_retry) + " attempts.") msg = '<p style="color: red;font-weight: bold;">ユーザIDかパスワードが間違っています(*回目)</p>'.replace( "*", str(error_retry)) sql = "insert into errortable values ('" + user_id_md5 + "','" + datetime.datetime.now( ).strftime("%Y-%m-%d %H:%M:%S") + "');" cursor.execute(sql) connector.commit() else: user_id = user[0] lock = user[1]