def login(name=None): if request.method == 'POST': username = request.form['username'] password = request.form['password'] # print(username, password) error = None user = auth(username=username, password=password, status='username if have') if user is None: error = 'Incorrect username' flash(error) return redirect(url_for('login')) status = auth(username=username, password=password, status='verify') if status is None: error = 'Incorrect password' flash(error) return render_template('login.html') elif status is True: session.clear() session['user_id'] = username flash("login finish") return redirect(url_for('index')) return render_template('login.html')
def signup(): auth_status = auth() if auth_status[0]: return redirect(url_for('index')) return render_template('signup.html', signed_in=auth_status[0], user=auth_status[1])
def get_weekly(request: Request, credentials: HTTPBasicCredentials = Depends(security)): # 認証 username = auth(credentials) # ユーザ情報を取得 user = db.session.query(User).filter(User.username == username).first() # タスクを取得 task = db.session.query(Task).filter(Task.user_id == user.id).all() db.session.close() # """ [new] 今日の日付と来週の日付""" today = datetime.now() + timedelta(hours=9) # 標準時から日本時間に変換 next_w = today + timedelta(days=7) # 1週間後の日付 # 直近のタスクだけでいいので、リストを書き換える task_weekly = [t for t in task if today <= t.deadline <= next_w] # JSONフォーマット task_weekly_json = [{ 'id': t.id, 'content': t.content, 'deadline': t.deadline.strftime('%Y-%m-%d %H:%M:%S'), 'published': t.date.strftime('%Y-%m-%d %H:%M:%S'), 'done': t.done, } for t in task_weekly] return task_weekly_json # curl -u username:password http://127.0.0.1:8000/get_weekly
def signin(): auth_status = auth() if request.method == "GET": if not auth_status[0]: return render_template('login.html', signed_in=auth_status[0], user=auth_status[1]) else: return redirect(url_for('index')) if request.method == "POST": if db.authenticate(request.form["un"], request.form["pw"]): if request.form.get('session'): session["USERNAME"] = request.form["un"] session["PASSWORD"] = request.form["pw"] else: flash('You must check \"keep me logged in\" to sign in') return redirect(url_for('signin')) flash("successfully logged in") else: flash("wrong username or password") return redirect(url_for('signin')) return redirect(url_for('signin'))
def get_gtm(**kwargs): var_id = kwargs['variable'] key_file = auth.auth('cj_data') SCOPES = ['https://www.googleapis.com/auth/tagmanager.readonly'] credentials = ServiceAccountCredentials.from_json_keyfile_dict( key_file, SCOPES) tag_manager = build('tagmanager', 'v2', credentials=credentials) path = 'accounts/1090055821/containers/6311504/workspaces/1000189/variables/' + var_id frame = pd.DataFrame() variable = tag_manager.accounts().containers().workspaces().variables( ).get(path=path).execute() para_list = variable['parameter'] x = next(item for item in para_list if item['key'] == 'map') y = x['list'] for item in y: url = item['map'][0]['value'] value = item['map'][1]['value'] row = {'url': url, 'value': value} frame = frame.append(row, ignore_index=True) frame['rate'] = frame['value'].str.extract('(?<=rate=)(.*?)(?=;|$)', expand=False) frame['owner'] = frame['value'].str.extract('(?<=owner=)(.*?)(?=;|$)', expand=False) frame['users'] = frame['value'].str.extract('(?<=users=)(.*?)(?=;|$)', expand=False) return frame
def search_console(startDate, endDate, startRow): key_file = auth.auth('cj_data') SCOPES = ['https://www.googleapis.com/auth/webmasters.readonly'] credentials = ServiceAccountCredentials.from_json_keyfile_dict( key_file, SCOPES) search_console = build('webmasters', 'v3', credentials=credentials) property_uri = 'https://www.citizensadvice.org.uk/' # test request to get a list of sites site_list = search_console.sites().list().execute() # dates are in the format YYYY-MM-DD request = { 'startDate': startDate, 'endDate': endDate, 'dimensions': ['query', 'device', 'page', 'date'], 'searchType': 'web', 'rowLimit': 25000, 'startRow': startRow } response = search_console.searchanalytics().query(siteUrl=property_uri, body=request).execute() if len(response) > 1: rows = response['rows'] df = pd.DataFrame.from_dict(rows) df[['query', 'device', 'page', 'date']] = pd.DataFrame(df['keys'].values.tolist(), index=df.index) result = df.drop(['keys'], axis=1) return result else: pass
def __init__(self, key, rename=None): self.hostid_value = {} self.name_value = {} self.key = key self.rename = rename auth_id = auth.auth() self.list_item = { "jsonrpc": "2.0", "method": "item.get", "params": { "output": "extend", "search": { "key_": self.key }, "selectInterfaces": ["interfaceid", "ip"], "sortfield": "name" }, "auth": auth_id, "id": 2 } hosts = requests.get(auth.url, headers=header, data=json.dumps(self.list_item)) for i in hosts.json()['result']: self.hostid_value[i["interfaces"][0]["ip"]] = i["lastvalue"]
async def chat(request: Request, credentials: HTTPBasicCredentials = Depends(security)): # Authに投げる username = auth(credentials) # userdata user = db.session.query(User).filter(User.username == username).first() db.session.close() # 今日の日付と来週の日付 today = datetime.datetime.now() if request.method == 'GET': return templates.TemplateResponse('chatbot.html', { 'request': request, 'user': user, 'messages': messages }) if request.method == 'POST': data = await request.form() human_to = data.get('messageText') #返すメッセージ表 messages.insert(0, username + ":" + human_to) bot_rep = human_to print("Bot reply to " + username + ":" + "[" + human_to + "]" + " to " + "[" + human_to + "]") messages.insert(0, "TwitterBot: @" + username + " " + bot_rep) return templates.TemplateResponse('chatbot.html', { 'request': request, 'user': user, 'messages': messages })
def update(id): auth_status = auth() if not auth_status[0]: flash('You must be logged in to update a blog post') return redirect(url_for('login')) current_post = collection.find_one({'_id': ObjectId(id)}) posted_by = current_post['posted_by'] if ObjectId(auth_status[1].id) != posted_by: return redirect(url_for('index')) if not (request.form['description'].strip() and request.form['content'].strip()): flash('You cannot have an empty input field.') return redirect(url_for('blogs.myblogs')) collection.update_one( { '_id': current_post['_id'], 'posted_by': ObjectId(auth_status[1].id) }, { "$set": { 'posted_by': auth_status[1].id, 'description': request.form['description'], 'content': request.form['content'] } }) flash('Post Updated Successfully!') return redirect(url_for('blogs.myblogs'))
def login(base_url="https://winkapi.quirky.com", config_file="config.cfg"): """ Request authentication information from the user, make the authentication request, and write the credentials to the specified configuration file. """ auth_info = dict(base_url=base_url, ) # request information from the user for k in [ "client_id", "client_secret", "username", "password", ]: auth_info[k] = raw_input("%s? " % k) try: auth_result = auth(**auth_info) except RuntimeError as e: print "Authentication failed. :(" print e else: print "Authentication success! ;-)" cf = ConfigFile(config_file) cf.save(auth_result)
def login(base_url="https://winkapi.quirky.com", config_file="config.cfg", client_id="", client_secret="", username="", password=""): """ Request authentication information from the user, make the authentication request, and write the credentials to the specified configuration file. """ auth_info = dict(base_url=base_url, ) print 'Essai d\'authentification avec : ' + client_id + ' ' + client_secret + ' ' + username + ' ' + password auth_info["client_id"] = client_id auth_info["client_secret"] = client_secret auth_info["username"] = username auth_info["password"] = password try: auth_result = auth(**auth_info) except RuntimeError as e: print "Probleme d\'authentification :(" print e else: print "Authentication reussie! ;-) Vous pouvez fermer cette fenetre" cf = ConfigFile(config_file) cf.save(auth_result)
def record_pkg(self, path): # sanity check string if not path or len( path) > MaxPathLength or not self.is_valid_package_path(path): return False # look in datastore key = 'pkg-' + path p = Package.get_by_key_name(key) if p is None: # not in datastore - verify URL before creating web, check_url = vc_to_web(path) if not web: logging.error('unrecognized path: %s', path) return False if not self.can_get_url(check_url): logging.error('cannot get %s', check_url) return False p = Package(key_name=key, path=path, count=0, web_url=web) if auth(self.request): # builder updating package metadata p.info = self.request.get('info') p.ok = self.request.get('ok') == "true" if p.ok: p.last_ok = datetime.datetime.utcnow() else: # goinstall reporting an install p.inc() p.last_install = datetime.datetime.utcnow() # update package object p.put() return True
def detail(request: Request, username, year, month, day, credentials: HTTPBasicCredentials = Depends(security)): """ URLパターンは引数で取得可能 """ username_temp = auth(credentials) if username_temp != username: return RedirectResponse('/') user = db.session.query(User).filter(User.username == username).first() task = db.session.query(Task).filter(Task.user_id == user.id).all() theday = '{}{}{}'.format(year, month.zfill(2), day.zfill(2)) task = [t for t in task if t.deadline.strftime('%Y%m%d') == theday] return templates.TemplateResponse( 'detail.html', { 'request': request, 'username': username, 'task': task, 'year': year, 'month': month, 'day': day })
def change_username(): auth_status = auth() if not auth_status[0]: return redirect(url_for('index')) if request.method == 'GET': return redirect(url_for('settings.index')) if user_exists(request.form['username']): flash(f'Username: {request.form["username"]} is already in use') return redirect(url_for('settings.index')) if not authenticate(auth_status[1].username, request.form['password']): flash('Incorrect current password, your username has NOT changed') return redirect(url_for('settings.index')) collection.update_one( {'_id': auth_status[1].id}, { '$set': { 'username': request.form['username'] }} ) session['USERNAME'] = request.form['username'] flash(f'Username changed from {auth_status[1].username} to {request.form["username"]}') return redirect(url_for('settings.index'))
def main(argv): scope = ['https://www.googleapis.com/auth/analytics.edit'] parser = argparse.ArgumentParser(description='Create and link filters to a Google Analytics account/profile. You will need the Google Analytics Account ID, Web Property ID (UA-XXXXX-Y), and the Profile ID at hand. You can find the Account ID and Profile ID in the URL of the Google Analytics UI (when viewing any profile). Account ID is the numerical string after \'a\' and Profile ID is the numerical string after \'p\' in the URL\'s /aXXXXwXXXXpXXXX part.') required = parser.add_argument_group('required arguments') required.add_argument('-c', '--create', metavar='accountid', help='Create the filters in the given Google Analytics account ID', required=True, dest='accountid') required.add_argument('-j', '--jsonpath', help='The path to the JSON file', required=True, metavar='/path/to/file.json') parser.add_argument('path_to_client_secrets', help='Path to your client_secrets file') args = parser.parse_args() account_id = args.accountid json_path = args.jsonpath client_secrets_path = args.path_to_client_secrets service = auth.auth('analytics', 'v3', scope, client_secrets_path) created_filters = create_filters(service, json_path, account_id) yes_no = False while yes_no not in ['y', 'n']: yes_no = raw_input('Do you wish to link these filters to a Google Analytics profile (y/n)? ') if yes_no is 'n': sys.exit() link_filters(service, created_filters, account_id)
async def add(request: Request, credentials: HTTPBasicCredentials = Depends(security)): # 認証 username = auth(credentials) # ユーザ情報を取得 user = db.session.query(User).filter(User.username == username).first() # フォームからデータを取得 data = await request.form() print(data) year = int(data['year']) month = int(data['month']) day = int(data['day']) hour = int(data['hour']) minute = int(data['minute']) deadline = datetime(year=year, month=month, day=day, hour=hour, minute=minute) # 新しくタスクを生成しコミット task = Task(user.id, data['content'], deadline) db.session.add(task) db.session.commit() db.session.close() return RedirectResponse('/admin')
def login(self): self.db_interface = auth.auth() username = self.usernameBox.get() password = self.passwordBox.get() if (self.db_interface.login_auth(username, password) == False): tk.Label(self, text="Incorrect Credentials", fg="red", font="none 11").pack() username = None password = None else: self.master.withdraw() # update the params structure with the user specific values user_params = self.db_interface.get_fetch() for key in user_params: if isinstance(p.params[key], p.NonNumericParam): programmable_strings = p.params[key].get_strings() s = programmable_strings[user_params[key]] p.params[key].set(s) else: p.params[key].set(user_params[key]) win_login = MainWin(master=self.master) win_login.title("Pacemaker DCM")
def detail(request: Request, username, year, month, day, credentials: HTTPBasicCredentials = Depends(security)): #認証 username_tmp = auth(credentials) #他のユーザーが訪問してきたら弾く if username_tmp != username: return RedirectResponse('/') #ログインユーザを取得 user = db.session.query(User).filter(User.username == username).first() #ログインユーザのタスクを取得 task = db.session.query(Task).filter(Task.user_id == user.id).all() db.session.close() #該当の日付と一致するするものだけのリストにする #月日は0埋め theday = '{}{}{}'.format(year, month.zfill(2), day.zfill(2)) task = [t for t in task if t.deadline.strftime('%Y%m%d') == theday] return templates.TemplateResponse( 'detail.html', { 'request': request, 'username': username, 'task': task, 'year': year, 'month': month, 'day': day })
def admin(request: Request, credentials: HTTPBasicCredentials = Depends(security)): username = auth(credentials) user = db.session.query(User).filter(User.username == username).first() task = db.session.query(Task).filter(Task.user_id == user.id).all() db.session.close() # 今日の日付と来週の日付 today = datetime.now() next_w = today + timedelta(days=7) # 1週間後の日付 """ [new] カレンダー関連 """ # カレンダーをHTML形式で取得 cal = MyCalendar(username, {t.deadline.strftime('%Y%m%d'): t.done for t in task}) # 予定がある日付をキーとして渡す cal = cal.formatyear(today.year, 4) # カレンダーをHTMLで取得 # 直近のタスクだけでいいので、リストを書き換える task = [t for t in task if today <= t.deadline <= next_w] links = [ t.deadline.strftime('/todo/' + username + '/%Y/%m/%d') for t in task ] # 直近の予定リンク return templates.TemplateResponse( 'admin.html', { 'request': request, 'user': user, 'task': task, 'links': links, 'calender': cal })
def RegisterButton(self): NewUser = self.username.get() NewPass = self.password.get() NewPass2 = self.password2.get() self.start = auth.auth() if (NewUser == "") or (NewPass == ""): tk.Label(self, text="Invalid Input", fg="red", font="none 12 bold").pack() elif (NewPass != NewPass2): tk.Label(self, text="Passwords do not match", fg="red", font="none 12 bold").pack() else: if (self.start.reg_auth(NewUser, NewPass) == (True, False, False)): tk.Label(self, text="Successful", fg="green", font="none 12 bold").pack() elif (self.start.reg_auth(NewUser, NewPass) == (False, False, True)): tk.Label(self, text="User Already Exists", fg="red", font="none 12 bold").pack() elif (self.start.reg_auth(NewUser, NewPass) == (False, True, False)): tk.Label(self, text="Max Users", fg="red", font="none 12 bold").pack() elif (self.start.reg_auth(NewUser, NewPass) == (False, True, True)): tk.Label(self, text="Max Users", fg="red", font="none 12 bold").pack()
def login(base_url="https://winkapi.quirky.com", config_file="config.cfg"): """ Request authentication information from the user, make the authentication request, and write the credentials to the specified configuration file. """ auth_info = dict( base_url=base_url, ) # request information from the user for k in [ "client_id", "client_secret", "username", "password", ]: auth_info[k] = raw_input("%s? " % k) try: auth_result = auth(**auth_info) except RuntimeError as e: print "Authentication failed. :(" print e else: print "Authentication success! ;-)" cf = ConfigFile(config_file) cf.save(auth_result)
def send_emails(request): SCOPES = 'https://mail.google.com/' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'baietii' authInst = auth.auth(SCOPES, CLIENT_SECRET_FILE, APPLICATION_NAME) credentials = authInst.get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) data = request.get_json(silent=True) url = 'https://us-central1-baietii.cloudfunctions.net/maps' r = requests.post((url), json={"location": data["location"]}) sendInst = send_email.send_email(service) for guest in data['guests']: html = '<html><head></head><body><p>Userul cu emailul ' + data[ 'email'] + ' te-a invitat la eveniment.</p><p>Descrierea evenimentului este:' + data[ 'description'] + '</p>' + '<img src =' + r.text + '><p>Click pe următorul link pentru a accepta: https://ccinvite.appspot.com?email=' + guest + '</p></body></html>' message = sendInst.create_message( '*****@*****.**', guest, data['email'] + ' invate you to...', html) sendInst.send_message('me', message) responseJson = {'msg': "Success"} headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '3600' } return (json.dumps(responseJson), 200, headers)
async def insert(request: Request, content: str = Form(...), deadline: str = Form(...), credentials: HTTPBasicCredentials = Depends(security)): """ タスクを追加してJSONで新規タスクを返す。「deadline」は%Y-%m-%d_%H:%M:%S (e.g. 2019-11-03_12:30:00)の形式 """ # 認証 username = auth(credentials) # ユーザ情報を取得 user = db.session.query(User).filter(User.username == username).first() # タスクを追加 task = Task(user.id, content, datetime.strptime(deadline, '%Y-%m-%d_%H:%M:%S')) db.session.add(task) db.session.commit() # テーブルから新しく追加したタスクを取得する task = db.session.query(Task).all()[-1] db.session.close() # 新規タスクをJSONで返す return { 'id': task.id, 'content': task.content, 'deadline': task.deadline.strftime('%Y-%m-%d %H:%M:%S'), 'published': task.date.strftime('%Y-%m-%d %H:%M:%S'), 'done': task.done, }
async def done(request: Request, credentials: HTTPBasicCredentials = Depends(security)): #print("t.done") # 認証オーケー? username = auth(credentials) # ユーザー名を取得 user = db.session.query(User).filter(User.username == username).first() # ログインユーザのタスクを取得 task = db.session.query(Task).filter(Task.user_id == user.id).all() # フォームで受け取ったタスクの終了判定を見て内容を変更する data = await request.form() t_dones = data.getlist('done[]') # リストとして取得 for t in task: if str(t.id) in t_dones: # もしIDが一致すれば"終了した予定"となるfale t.done = True db.session.commit() db.session.close() return RedirectResponse('/admin')
def change_password(): auth_status = auth() if not auth_status[0]: return redirect(url_for('index')) if request.method == 'GET': return redirect(url_for('settings.index')) if not authenticate(auth_status[1].username, request.form['currentPassword']): flash('Incorrect current password, your password has NOT changed') return redirect(url_for('settings.index')) if request.form['newPassword'] != request.form['newPassword2']: flash('Your passwords did not match') return redirect(url_for('settings.index')) collection.update_one( {'_id': auth_status[1].id}, { '$set': { 'password': enc.encrypt(request.form['newPassword']) }} ) session['PASSWORD'] = request.form['newPassword'] flash('Password successfully changed, make sure to save it!') return redirect(url_for('settings.index'))
def login(base_url="https://winkapi.quirky.com", config_file="config.cfg",client_id="",client_secret="",username="",password=""): """ Request authentication information from the user, make the authentication request, and write the credentials to the specified configuration file. """ auth_info = dict( base_url=base_url, ) print 'Essai d\'authentification avec : '+client_id + ' ' +client_secret+' '+username+' '+password auth_info["client_id"] = client_id auth_info["client_secret"] = client_secret auth_info["username"] = username auth_info["password"] = password try: auth_result = auth(**auth_info) except RuntimeError as e: print "Probleme d\'authentification :(" print e else: print "Authentication reussie! ;-) Vous pouvez fermer cette fenetre" cf = ConfigFile(config_file) cf.save(auth_result)
def record_pkg(self, path): # sanity check string if not path or len(path) > MaxPathLength or not self.is_valid_package_path(path): return False # look in datastore key = 'pkg-' + path p = Package.get_by_key_name(key) if p is None: # not in datastore - verify URL before creating web, check_url = vc_to_web(path) if not web: logging.error('unrecognized path: %s', path) return False if not self.can_get_url(check_url): logging.error('cannot get %s', check_url) return False p = Package(key_name = key, path = path, count = 0, web_url = web) if auth(self.request): # builder updating package metadata p.info = self.request.get('info') p.ok = self.request.get('ok') == "true" if p.ok: p.last_ok = datetime.datetime.utcnow() else: # goinstall reporting an install p.inc() p.last_install = datetime.datetime.utcnow() # update package object p.put() return True
def __getLiveVideoInfo(self, id, geolocation): username = control.setting('globoplay_username') password = control.setting('globoplay_password') # authenticateurl credentials = auth.auth().authenticate(username, password) affiliate = control.setting('globo_affiliate') if affiliate == "All" and geolocation != None: pass elif affiliate == "Sao Paulo": geolocation = 'lat=-23.5505&long=-46.6333' elif affiliate == 'Brasilia': geolocation = 'lat=-15.7942&long=-47.8825' elif affiliate == 'Belo Horizonte': geolocation = 'lat=-19.9245&long=-43.9352' else: #Rio de Janeiro geolocation = 'lat=-22.900&long=-43.172' post_data = "%s&player=%s&version=%s" % (geolocation, PLAYER_SLUG, PLAYER_VERSION) #4452349 hashUrl = 'http://security.video.globo.com/videos/%s/hash' % id hashJson = client.request(hashUrl, error=True, cookie=credentials, mobile=True, headers={ "Accept-Encoding": "gzip", "Content-Type": "application/x-www-form-urlencoded", "User-Agent": "Globo Play/0 (iPhone)" }, post=post_data) return { "id": "-1", "title": hashJson["name"], # "program": playlistJson["program"], # "program_id": playlistJson["program_id"], # "provider_id": playlistJson["provider_id"], # "channel": playlistJson["channel"], # "channel_id": playlistJson["channel_id"], "category": 'Live', # "subscriber_only": playlistJson["subscriber_only"], "subscriber_only": 'true', # "exhibited_at": playlistJson["exhibited_at"], "player": PLAYER_SLUG, "url": hashJson["url"], "query_string_template": "h={{hash}}&k={{key}}&a={{openClosed}}&u={{user}}", "thumbUri": hashJson["thumbUri"], "hash": hashJson["hash"], "user": hashJson["user"], "credentials": credentials }
def POST(self): a=auth.auth() data=web.input() # ausgabe+= "login " + data['login'] + "\n" #ausgabe+="pw " + data['password'] + " " + hashedpw.hexdigest() + "\n" if a.authenticate(data['login'],data['password']): return "Login erfolgreich!" return "Login failt!"
async def bot_reply(sendMessage,request:Request, credentials: HTTPBasicCredentials = Depends(security)): bot = GenerativeSystem() username = auth(credentials) #messages.append("test") bot_rep = bot.reply(sendMessage) #data.messageText print("Bot reply to" + username + ":" + bot_rep) return bot_rep
def main(argv): scope = ['https://www.googleapis.com/auth/analytics.edit'] parser = argparse.ArgumentParser( description= 'List and mass update Google Analytics data retention settings per web property.' ) group = parser.add_mutually_exclusive_group(required=True) group.add_argument( '-c', '--create', help= 'create CSV-file of all web properties and their data retention settings', action='store_true') group.add_argument( '-u', '--update', metavar='PATH', help='path to the CSV-file that is the source for the mass update') parser.add_argument('path_to_client_secrets', help='path to your client_secrets file') args = parser.parse_args() client_secrets_path = args.path_to_client_secrets service = auth.auth('analytics', 'v3', scope, client_secrets_path) if args.create: if not os.path.exists('csv'): os.makedirs('csv') with open('csv/data_retention_list.csv', 'w') as myfile: wr = csv.writer(myfile) wr.writerow(HEADERS) hierarchy = build_hierarchy(service) print('Writing data to CSV...') for account in hierarchy: for property in hierarchy[account]['properties']: wr.writerow([ hierarchy[account]['account_name'].encode('utf-8'), hierarchy[account]['account_id'], hierarchy[account]['properties'][property] ['property_name'].encode('utf-8'), hierarchy[account] ['properties'][property]['property_id'], hierarchy[account]['properties'][property] ['data_retention_ttl'], hierarchy[account] ['properties'][property]['data_retention_reset'] ]) print( 'All done! File data_retention_list.csv has been written in the csv/ folder.' ) if args.update: path = args.update print('Validating CSV file structure...') if not path.lower().endswith('.csv'): print('The file must have the .csv filetype!') else: parse_csv_and_update(path, service)
def auth_message(message,phone): content = json.loads(message.content['text']) if content['cd'] == 'auth': #进行认证操作 status = auth(phone,content['mobile']) if status is True: cache.set('%s_auth_status'% phone,True,30) else: cache.set('%s_auth_status'% phone,False,30)
def authorized_write(self): password = auth() cryptic_password,password_key = self.encrypt(password) try: with open(self.ofile,'w') as f: # create/open an output file f.write('\n'.join([self.decryption_key,self.encrypted_text])) f.write('\n-k-' + ' '.join([cryptic_password,password_key])) except IOError: self.error = "Output file couldn't be created/opened. Check directory read/write permissions"
def __init__(self): SCOPES = 'https://www.googleapis.com/auth/drive' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Drive API Python Quickstart' authInst = auth.auth(SCOPES, CLIENT_SECRET_FILE, APPLICATION_NAME) credentials = authInst.getCredentials() http = credentials.authorize(httplib2.Http()) global drive_service drive_service = discovery.build('drive', 'v3', http=http)
def get_tuits(n, hashtag): api = auth.auth() tuits = [] for status in tweepy.Cursor(api.search, q=hashtag).items(n): tuit = json.dumps(status.text) tuits.append(tuit) with open('DATASETS/tuits-{}-{}.json'.format(n, hashtag), 'w') as outfile: json.dump(tuits, outfile)
def verify(self): if (self._key_img.image is not None and self._watermark_img.image is not None): wm = auth( self._watermark_img.image, self._key_img.image ) self.insert_image(self._verify_img, filename='watermark.png') else: raise ValueError('share can be made from share and input image')
def __init__(self, remoteShell, domainAdmin="admin", domain=None): self.remoteShell = remoteShell self.vastoolPath = "/opt/quest/bin/vastool" self.domainAdmin = domainAdmin self.defaultDomain = domain self.info = info.info(self.run) self.flush = flush.flush(self.run) self.create = create.create(self.run, self.defaultDomain) self.delete = delete.delete(self.run) self.timesync = timesync.timesync(self.run) self.nss = nss.nss(self.run) self.group = group.group(self.run) self.isvas = isvas.isvas(self.run) self.list = list.list(self.run) self.auth = auth.auth(self.run, self.defaultDomain) self.cache = cache.cache(self.run) self.configure = configure.configure(self.run) self.configureVas = configureVas.configureVas(self.run) self.schema = schema.schema(self.run) self.merge = merge.merge(self.run) self.unmerge = unmerge.unmerge(self.run) self.user = User.user(self.run) self.ktutil = ktutil.ktutil(self.run) self.load = load.load(self.run) self._license = License.License(self.run) self.License = self._license.License self.parseLicense = self._license.parseLicense self.compareLicenses = self._license.compareLicenses #self.vasUtilities = vasUtilities.vasUtilities(self.remoteShell) self.unconfigure = unconfigure.unconfigure(self.run) self.nssdiag = nssdiag(self.run) isinstance(self.info, info.info) isinstance(self.flush, flush.flush) isinstance(self.create, create.create) isinstance(self.delete, delete.delete) isinstance(self.timesync, timesync.timesync) isinstance(self.nss, nss.nss) isinstance(self.group, group.group) isinstance(self.isvas, isvas.isvas) isinstance(self.list, list.list) isinstance(self.auth, auth.auth) isinstance(self.cache, cache.cache) isinstance(self.configure, configure.configure) isinstance(self.configureVas, configureVas.configureVas) isinstance(self.schema, schema.schema) isinstance(self.merge, merge.merge) isinstance(self.unmerge, unmerge.unmerge) isinstance(self.user, User.user) isinstance(self.ktutil, ktutil.ktutil) isinstance(self.load, load.load) #isinstance(self.vasUtilities, vasUtilities.vasUtilities) isinstance(self.unconfigure, unconfigure.unconfigure) isinstance(self.nssdiag, nssdiag)
def post(self): if not auth(self.request): self.response.set_status(403) return builder = self.request.get('builder') log = self.request.get('log').encode('utf-8') loghash = '' if len(log) > 0: loghash = hashlib.sha256(log).hexdigest() l = CompressedLog(key_name=loghash) l.log = bz2.compress(log) l.put() node = self.request.get('node') if not validNode(node): logging.error('Invalid node %s' % (node)) self.response.set_status(500) return n = nodeByHash(node) if n is None: logging.error('Cannot find node %s' % (node)) self.response.set_status(404) return nn = n def add_build(): n = nodeByHash(node, ancestor=nn) if n is None: logging.error('Cannot find hash in add_build: %s %s' % (builder, node)) return s = '%s`%s' % (builder, loghash) for i, b in enumerate(n.builds): if b.split('`', 1)[0] == builder: # logging.error('Found result for %s %s already' % (builder, node)) n.builds[i] = s break else: # logging.error('Added result for %s %s' % (builder, node)) n.builds.append(s) n.put() db.run_in_transaction(add_build) key = 'todo-%s' % builder memcache.delete(key) c = getBrokenCommit(node, builder) if c is not None and not c.fail_notification_sent: notifyBroken(c, builder) self.response.set_status(200)
def login(): if 'username' in session: return redirect(url_for('home')) elif request.method == 'GET': return render_template('login.html') username = request.form['Username'] password = request.form['Password'] if auth.auth(username,password): return redirect(url_for('home')) return render_template('login.html', message = 'Invalid combo')
def login(): if request.method == 'POST': username = request.form.get('user') password = request.form.get('pass') endpoint = request.form.get('endpoint') if auth.auth(username, password): session['username'] = username session['admin'] = auth.is_admin(username) flash('Login successfull.', 'success') else: flash('Login failed.', 'error') return redirect(url_for(endpoint)) return redirect(url_for('index'))
def login(): if request.method == "GET": return render_template("login.html") else: user = request.form['name'] pas = request.form['pass'] button = request.form['button'] if auth.auth(user,pas): return render_template("loggedin.html") else: error = "Invalid Username/Password. Try Again!" return render_template("login.html",e = error)
def main(): """ The main function """ parser = argparse.ArgumentParser(description='Encrypt and decrypt specified files') parser.add_argument('-D', help='Directory to start encrypting files in', dest="directory", required="True") parser.add_argument('-R', help='Specify whether to recurse down directories', dest="recurse", action="store_true", default=False) parser.add_argument('-A', help='Action to perform [encrypt/decrypt]', dest="action", required="True") parser.add_argument('-K', help='The key to use with the RC4 cipher', dest="key", required="True") parser.add_argument('-C', help='Clean up (delete) the input files (default no)', dest="cleanup", action="store_true", default=False) parser.add_argument('-V', help='Verbose output', dest="verbose", action="store_true", default=False) args = parser.parse_args() # perform authentication login = auth() login.attempt_login() # if the login creds were not correct, exit the program if login.login == False: print "Unsuccessful login." sys.exit(1) # check if the action is either "encrypt" or "decrypt" if args.action == "encrypt": action = "Encrypt" elif args.action == "decrypt": action = "Decrypt" else: print "ERROR: the -A flag should have an argument of either encrypt or decrypt (case sensitive)" sys.exit(1) # check authorization for requested action here (attacker can encrypt, admin can enc/dec, etc) x = xacmlparser() e = xml.etree.ElementTree.parse('rights.xacml') root = e.getroot() # parse_action will return True if the user is authorized to perform the requested action execute = x.parse_action(root,login.group,action) if execute: perform_action(args) else: print "User is not authorized to perform the requested action" sys.exit(1)
def dispatch_page(page): if page == 'home': page = '' m = web.input().get('m', 'view') m = re.sub(r'[\-\.]', '_', m) jt.update({'mode': 'page', 'method': m}) if not auth.auth(m): return auth.signin_required() mode = modes['page']() m = web.ctx.method+'_'+m if not hasattr(mode, m): return web.badrequest() if page: return getattr(mode, m)(page) else: return getattr(mode, m)()
def auth(self,client_user): print("user:%s"%client_user) self.request.send(bytes("331 %s"%(self.code_msg["331"]).format(client_user),"utf-8")) r_data = self.request.recv(1024).decode() r_data_cmd ,client_pass = re.split(r"\s",r_data,1) client_pass = client_pass.strip() print("pass:%s"%client_pass) if r_data_cmd == "PASS": self.homedir = auth.auth(client_user,client_pass) if self.homedir != None: self.homedir = os.path.abspath(self.homedir) self.current_dir = self.homedir print("homedir:%s"%self.homedir) self.request.send(bytes(("230 %s"%self.code_msg["230"]).format(client_user),"utf-8")) self.login_status = True else: self.request.send(bytes(("530 %s"%self.code_msg["530"]),"utf-8")) self.login_status = False
def uploadFile(self): #get credentials for googleAPI SCOPES = 'https://www.googleapis.com/auth/drive' CLIENT_SECRET_FILE = '/scripts/MonetStaffScheduler/client_secret_IB.json' #CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Drive API Python Quickstart' authInst = auth.auth(SCOPES,CLIENT_SECRET_FILE,APPLICATION_NAME) credentials = authInst.getCredentials() #authorize with googleAPI and upload csv as google sheet http = credentials.authorize(httplib2.Http()) drive_service = discovery.build('drive', 'v3', http=http) file_metadata = {'name': self.FILENAME, 'mimeType': 'application/vnd.google-apps.spreadsheet'} media = MediaFileUpload(self.FILEPATH, mimetype=self.MIMETYPE) #check list of files in google drive for StaffSchedule; if found, get fileID notFound = True fileID = drive_service.files().list().execute() #array of file id's sheetIds = [] #print (fileID) for i in range(0, len(fileID['files'])): #print (self.FILENAME) if self.FILENAME in fileID['files'][i]['name'] + '.csv': #print(fileID['files'][i]['name']) file = drive_service.files().update(fileId=fileID['files'][i]['id'], body=file_metadata, media_body=media, fields='id').execute() notFound = False #if StaffSchedule sheet not found, create a new one if notFound == True: file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute() print('File ID: %s' % file.get('id')) print('Sheet updated') return (file.get('id'))
def parse(self, buffer): # parse the messages buffer = buffer.split() length = len(buffer) if length > 0 and buffer[0] == "PING": self.ping(buffer) elif length > 1 and (buffer[1] == "376" or buffer[1] == "422"): self.connected = 1 self._join() self.auth = auth.auth(self) self.auth.auth_levels[config.bot_master.lower()] = 10 elif length > 1 and buffer[1] == "330": if "is logged in as" in ' '.join(buffer): self.verify[buffer[3].lower()] = 1 return Message(buffer) elif length > 1 and buffer[1] == "307": if "is identified for this nick" in ' '.join(buffer): self.verify[buffer[3].lower()] = 1 if "is a registered nick" in ' '.join(buffer): self.verify[buffer[3].lower()] = 1 return Message(buffer) elif length > 1 and buffer[1] == "318": try: if self.verify[buffer[3].lower()] != 1: self.verify[buffer[3].lower()] = -1 except: self.verify[buffer[3].lower()] = -1 return Message(buffer) elif length > 1 and buffer[1] == "401": return Message(buffer) elif length > 2 and (buffer[1] == "PRIVMSG" or buffer[1] == "NOTICE" or buffer[1] == "JOIN" or buffer[1] == "PART" or buffer[1] == "QUIT" or buffer[1] == "NICK" or buffer[1] == "KICK"): return Message(buffer) return None
def dispatch_mode(mode, method): m = re.sub(r'[\-\.]', '_', method) jt.update({'mode': mode, 'method': m}) if not auth.auth(m): return auth.signin_required() mode = modes[mode]() m = (m and '_'+m) or '' webmeth = web.ctx.method if webmeth == "HEAD" and not hasattr(mode, webmeth + method): webmeth = "GET" m = webmeth + m if not hasattr(mode, m): return web.seeother('%s%s_/%s' % (jt.site.url, type(mode).__name__, method)) return getattr(mode, m)()
def _graph_timeline(self, times, counts, title): creds = auth('credentials.csv') plotly_username = creds['plotly_username'] plotly_key = creds['plotly_api_key'] py.sign_in(plotly_username, plotly_key) data = Data([ Scatter( x = times, y = counts ) ]) valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits) fname = ''.join(c for c in title if c in valid_chars) plot_url = py.plot(data, filename=fname) py.image.save_as({'data' : data}, 'images/%s.png' % fname) return plot_url, fname
def __init__(self, proxies={'http': 'http://127.0.0.1:8080', 'https': 'http://127.0.0.1:8080'}): """ Creates an instance of the ZAP api client. :Parameters: - `proxies`: dictionary of ZAP proxies to use. Note that all of the other classes in this directory are generated new ones will need to be manually added to this file """ self.__proxies = proxies self.acsrf = acsrf(self) self.ascan = ascan(self) self.auth = auth(self) self.autoupdate = autoupdate(self) self.context = context(self) self.core = core(self) self.params = params(self) self.pscan = pscan(self) self.search = search(self) self.spider = spider(self)
def main(): print "**************WELCOME****************\n" print "This is the interface for the program\n" #Phase 1 - Authenticating the identity. The following code will retreive the username and password and send it to the module auth.py auth_type = raw_input("Please select the type of authentication(Enter the number and press enter) \n\t1. Email\n\t2. LDAP\n\t\t:") if auth_type == '1': auth_str = "Email address" elif auth_type == '2': auth_str = "LDAP username" else: print "Invalid input" sys.exit() print "Please enter the " + auth_str + " that you want to use as your identity : " username = raw_input(auth_str + " : ") password = getpass.getpass("Please enter the password for your " + auth_str + " '" + username + "' : ") auth_result = auth.auth(username, password, auth_type) auth_result = "S" if auth_result is "S": print("Hello, " + username + ". Authentication has been successful. You can now use your username as your Identity\n") else: print("Authentication failed") print auth_result return
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import vk_api import auth vk = auth.auth(auth.result[0],auth.result[1]) class Profile: relation = {1: "Не женат/Не замужем", 2: "Есть друг/Есть подруга", 3: "Помолвлен/Помолвлена", 4: "Женат/Замужем", 5:"Все сложно", 6:"В активном поиске", 7:"Влюблён/Влюблена", 0: "Не указано"} '''Класс отвечающий за профиль''' def getProfileInfo(ids): try: info = vk.method('users.get', {"user_id": ids, "fields": "sex", "fields": "online"}) return "".join(info[0]["first_name"] + " " + info[0]["last_name"] + " " + "\ Онлайн: " + str(info[0]["online"]) + "\ ID: " + str(info[0]["id"])) except UnicodeEncodeError: pass def getProfileName(ids): try: info = vk.method('users.get', {"user_id": ids}) return "".join(info[0]["first_name"] + " " + info[0]["last_name"]) except UnicodeEncodeError: pass def getcurrentProfile(): info = vk.method('account.getProfileInfo') relation = {1: "Не женат/Не замужем", 2: "Есть друг/Есть подруга", 3: "Помолвлен/Помолвлена", 4: "Женат/Замужем", 5:"Все сложно", 6:"В активном поиске", 7:"Влюблён/Влюблена", 0: "Не указано"} return(''.join(info['first_name'] + " " + info['last_name'] + " \ ID: " + info['screen_name'] + "\nСтрана: " + info['country']['title'] + " \ " + "Дата рождения: " + info['bdate'] + "\nСемейное положение: " + relation[info['relation']]))
def post(self): if not auth(self.request): self.response.set_status(403) return self.authenticated_post()
from auth import auth from lxml import html import urllib2 import vkontakte email = "123" # password = "******" # vkID = "2951857" scope = "audio" # tehToken = 'e103d0a5b0bcca78e09654dbd5e00b509cce026e0265a25b0bf64f889a2f6da22b9f40a' # userID = 19237512 tehToken, userID = auth(email, password, vkID, scope) print(tehToken, userID) vk = vkontakte.API(token=tehToken) sresult = vk.audio.search(q="Mozart", count=5) tehURL = "https://api.vkontakte.ru/method/audio.get.xml?uid=" + userID + "&access_token=" + tehToken page = urllib2.urlopen(tehURL) rawHTML = page.read() try: doc = html.document_fromstring(rawHTML) except html.etree.ParserError: print("Parser error.") artistMas = [] number = 0 for artist in doc.cssselect("artist"): artistMas.append(artist.text) number += 1 try:
def continue_button_clicked(self,widget,data=None): self.username = self.username_entry.get_text() #print 'User Name : %s' %self.username self.password = self.password_entry.get_text() #print 'Password : %s' %self.password auth.auth(self.username,self.password)
def stringReceived(self, string): if self.__wait_auth: self.__auth_buffer.append(string) return (msg, params) = (string[0], string[1:]) logger.trace("Received from %s: %s", self.cid(), repr(string)) if not self.__logged_in: def login_failure(msg): logger.warn('Login failure from %s: %s', self.cid(), msg) self.sendString('F') self.__challenge = None # Prevent more attempts # Keep the connection open, but idle. Prevents very fast # reconnects. if msg == 'L': # Client wants to log in. # Extract parameters. (version, params) = (params[0], params[1:]) (cid, params) = extract_string(params) (response, params) = extract_string(params) self.__cid = cid if version == 'O': self.__cid = self.__cid.encode('hex') logger.debug('Client %s sent login info', self.cid()) if params != '': login_failure('Protocol violation') return log_info = None if version != 'O': login_failure('Login scheme not implemented') return # A callback once we receive decision if the client is allowed def auth_finished(allowed): self.__wait_auth = False if allowed: self.__authenticated = True # Replay the bufferend messages for message in self.__auth_buffer: self.stringReceived(message) else: login_failure('Incorrect password') self.__auth_buffer = None # Ask the authenticator if self.__challenge: auth.auth(auth_finished, self.__cid, self.__challenge.encode('hex'), response.encode('hex')) self.__wait_auth = True elif msg == 'H': if self.__authenticated: if len(params) >= 1: (self.__proto_version,) = struct.unpack("!B", params[0]) if self.__proto_version >= 1: self.__available_plugins = {} if self.__plugins.register_client(self): if self.__proto_version == 0: # Activate all the clients in the old version. # The new protocol handles activation on plugin-by-plugin basis for p in self.__plugins.get_plugins(): self.__plugins.activate_client(p, self) else: # Please tell me when there're changes to the allowed plugins plugin_versions.add_client(self) self.__logged_in = True self.__pinger = timers.timer(self.__ping, 45 if self.cid() in self.__fastpings else 120, False) activity.log_activity(self.cid(), "login") logger.info('Client %s logged in', self.cid()) else: return else: login_failure('Asked for session before loging in') return elif msg == 'S': if len(params) != 4: logger.warn("Wrong session ID length on client %s: %s", self.cid(), len(params)) return (self.session_id,) = struct.unpack("!I", params) return elif msg == 'P': # Ping. Answer pong. self.sendString('p' + params) elif msg == 'p': # Pong. Reset the watchdog count self.__pings_outstanding = 0 self.last_pong = time.time() elif msg == 'R': # Route data to a plugin (plugin, data) = extract_string(params) self.__plugins.route_to_plugin(plugin, data, self.cid()) # TODO: Handle the possibility the plugin doesn't exist somehow (#2705) elif msg == 'V': # New list of versions of the client if self.__proto_version == 0: self.__available_plugins = {} while len(params) > 0: (name, params) = extract_string(params) (version,) = struct.unpack('!H', params[:2]) self.__available_plugins[name] = version params = params[2:] else: self.__handle_versions(params) else: logger.warn("Unknown message from client %s: %s", self.cid(), msg)
def do_GET( self ): o = urllib.parse.urlparse( self.path ) path = o.path ms = self.headers[ "If-Modified-Since" ] if sett.server_dep != "windows dev": if ms is not None: tm = time.mktime( time.strptime( ms, '%a, %d %b %Y %H:%M:%S GMT' ) ) if tm >= common.env[ "Modified-Since" ]: self.ans_like_304( ) return #print( self.headers._headers[0][1] ) if True: if path == "/": self.ans_like_text_file( "html/index.html", "text/html" ) elif path[ -5: ] == ".html": self.ans_like_text_file( "html/" + path[ 1: ], "text/html" ) elif path[ -3: ] == ".js": self.ans_like_text_file( path[ 1: ], "text/javascript" ) elif path[ -4: ] == ".css": self.ans_like_text_file( path[ 1: ], "text/css" ) elif path[ -4: ] == ".ico": self.ans_like_text_file( path[ 1: ], "image/ico" ) elif path[ -4: ] == ".png": self.ans_like_text_file( path[ 1: ], "image/png" ) elif path[ -4: ] == ".svg": self.ans_like_text_file( path[ 1: ], "image/svg+xml" ) elif path[ -4: ] == ".xml": self.ans_like_text_file( path[ 1: ], "text/xml" ) elif path[ -4: ] == ".otf": self.ans_like_text_file( path[ 1: ], "font/opentype" ) elif path[0:9] == "/catalog/": html = scg.goods_main_view( path, "id" ) self.ans_like_text( html ) elif path[ -6: ] == "/goods": html = scg.goods_main_view( path ) if html == False: self.ans_like_404() else: self.ans_like_text( html ) elif path[ 0 : 8 ] == "/orders/": html = scg.orders( path[ 8: ] ) self.ans_like_text( html ) elif path[ 0 : 14 ] == "/getorderspdf/": self.ans_like_text_file( "out.pdf", """application/pdf;filename="out.pdf" """) elif path[0:10] == "/site-map/": html = scg.make_map( path[ 10: ] ) if html == False: self.ans_like_404() else: self.ans_like_text( html ) elif path == "/stat": if auth.auth( self.headers[ "Cookie" ] ): html = scg.stat() self.ans_like_text( html ) else: self.ans_like_404() elif path == "/allorders": if auth.auth( self.headers[ "Cookie" ] ): html = scg.allorders() self.ans_like_text( html ) else: self.ans_like_404() elif path == "/tam": html = tam.tam.index() self.ans_like_text( html ) else: self.ans_like_404() elif self.headers._headers[0][1] == 'http://eztf.ru': if path == "/": self.ans_like_text_file("/eztf/index.html","text/html") elif path[ -5: ] == ".html": self.ans_like_text_file( "html/" + path[ 1: ], "text/html" ) elif path[ -3: ] == ".js": self.ans_like_text_file( path[ 1: ], "text/javascript" ) elif path[ -4: ] == ".css": self.ans_like_text_file( path[ 1: ], "text/css" ) elif path[ -4: ] == ".ico": self.ans_like_text_file( path[ 1: ], "image/ico" ) elif path[ -4: ] == ".png": self.ans_like_text_file( path[ 1: ], "image/png" ) elif path[ -4: ] == ".svg": self.ans_like_text_file( path[ 1: ], "image/svg+xml" ) elif path[ -4: ] == ".xml": self.ans_like_text_file( path[ 1: ], "text/xml" ) elif path[ -4: ] == ".otf": self.ans_like_text_file( path[ 1: ], "font/opentype" )
import sending_mail try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None import auth import mesages SCOPES = 'https://mail.google.com/' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Gmail API Python Quickstart' authInst = auth.auth(SCOPES,CLIENT_SECRET_FILE,APPLICATION_NAME) credentials = authInst.get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) import base64 import email from apiclient import errors def GetMessage(service, me , msg_id): """Get a Message with given ID. Args: service: Authorized Gmail API service instance.
def GET(self): a=auth.auth() f=a.authform return render.login(title,"Login",f)
def _http(self, path, method, headers={}, body=None, expected="200"): # have we ever authed? if need_to_auth(**self.auth): if self.debug: print "Getting first access token" self.auth = auth(**self.auth) # see if we need to reauth? if need_to_reauth(**self.auth): if self.debug: print "Refreshing access token" # TODO add error handling self.auth = reauth(**self.auth) if self.auth_object is not None: self.auth_object.save(self.auth) if self.debug: print "Authentication being used:\n" \ "\tAccess token : %s\n" \ "\tRefresh token : %s" % (self.auth['access_token'], self.auth['refresh_token']) # add the auth header all_headers = self._headers() all_headers.update(headers) if body: all_headers.update(Wink.content_headers) if type(body) is not str: body = json.dumps(body) if self.debug: print "Request: %s %s" % (method, path) if headers: print "Extra headers:", headers if body: print "Body:", pprint(body) resp, content = self.http.request( self._url(path), method, headers=all_headers, body=body ) if self.debug: print "Response:", resp["status"] # coerce to JSON, if possible if content: try: content = json.loads(content) if "errors" in content and content["errors"]: raise RuntimeError("\n".join(content["errors"])) except: pass if self.debug: pprint(content) if type(expected) is str: expected = set([expected]) if resp["status"] not in expected: raise RuntimeError( "expected code %s, but got %s for %s %s" % ( expected, resp["status"], method, path, ) ) if content: return content return {}
def __init__(self): web.header('Content-Type','application/xml') auth_info = web.ctx.env.get('HTTP_AUTHORIZATION') auth.auth(auth_info)