def searchGithub(): githubUser = request.form['username'] response = requests.get('https://api.github.com/users/' + githubUser) html = json.load(response) reposUrl = html['repos_url'] repoList = requests.get(reposUrl) repoListJson = json.load(repoList) return json.dumps(repoListJson)
def resolve_conflicts(self): """ This is our Consensus Algorithm, it resolves conflicts by replacing our chain with the longest one in the network. :return: <bool> True if our chain was replaced, False if not """ neighbours = self.nodes new_chain = None # We're only looking for chains longer than ours max_length = len(self.chain) # Grab and verify the chains from all the nodes in our network for node in neighbours: response = requests.get(f'http://{node}/chain') if response.status_code == 200: length = response.json()['length'] chain = response.json()['chain'] # Check if the length is longer and the chain is valid if length > max_length and self.valid_chain(chain): max_length = length new_chain = chain # Replace our chain if we discovered a new, valid chain longer than ours if new_chain: self.chain = new_chain return True return False
def saving(): # 클라이언트로부터 데이터를 받는 부분 url_receive = request.form['url_give'] comment_receive = request.form['comment_give'] # meta tag를 스크래핑 하는 부분 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36' } data = requests.get(url_receive, headers=headers) soup = BeautifulSoup(data.text, 'html.parser') og_image = soup.select_one('meta[property="og:image"]') og_title = soup.select_one('meta[property="og:title"]') og_description = soup.select_one('meta[property="og:description"]') url_image = og_image['content'] url_title = og_title['content'] url_description = og_description['content'] # mongoDB에 넣는 부분 article = { 'url': url_receive, 'comment': comment_receive, 'image': url_image, 'title': url_title, 'desc': url_description } db.articles.insert_one(article) return jsonify({'result': 'success'})
def get_results(data): url = ( "http://api.nytimes.com/svc/search/v2/articlesearch.json?q=" + data + "&api-key=16544f21c00fca2a33169b99b96a4668%3A16%3A72957421" ) data = requests.get(url).json() return jsonify(result="This function would return search results", response=data), 201
def RemoveUser(): try: User=requests.get('user') if User in users: remove user else: return False except: return { "res":"Server Error" }
def findinfo(cname): totalresult = [] country = cname url = "https://www.worldometers.info/coronavirus/country/{countryname}/".format( countryname=country) response = requests.get(url) if response.status_code == 200: soup = BeautifulSoup(response.content, 'html.parser') result = soup.find_all('div', class_="maincounter-number") for i in result: totalresult.append(i.find("span").text) else: totalresult.append("No Result") return totalresult
def AddUser(): try: User=requests.get('user') if(User): if User in users: return "User Already Exists" else: users.append(User) return "User Added" else: return False except: return { "res":"Server Error" }
def download(url): req = requests.get(url, stream=True) return Response(stream_with_context(req.iter_content()), content_type=req.headers['content-type'])
def gconnect(): # Validate anti-forgery state token if request.args.get('state') != login_session['state']: response = make_response(json.dumps('Invalid state parameter.'), 401) response.headers['Content-Type'] = 'application/json' return response # Obtain authorization code code = request.data try: # Upgrade the authorization code into a credentials object oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(code) except FlowExchangeError: response = make_response(json.dumps('Failed to upgrade' 'the authorization code.'), 401) response.headers['Content-Type'] = 'application/json' return response # Check that the access token is valid. access_token = credentials.access_token url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?' 'access_token=%s' % access_token) h = httplib2.Http() result = json.loads(h.request(url, 'GET')[1]) # If there was an error in the access token info, abort. if result.get('error') is not None: response = make_response(json.dumps(result.get('error')), 500) response.headers['Content-Type'] = 'application/json' return response # Verify that the access token is used for the intended user. gplus_id = credentials.id_token['sub'] if result['user_id'] != gplus_id: response = make_response(json.dumps("Token's user ID doesn't match" "given user ID."), 401) response.headers['Content-Type'] = 'application/json' return response # Verify that the access token is valid for this app. if result['issued_to'] != CLIENT_ID: response = make_response(json.dumps("Token's client ID does not" "match app's."), 401) print "Token's client ID does not match app's." response.headers['Content-Type'] = 'application/json' return response stored_access_token = login_session.get('access_token') stored_gplus_id = login_session.get('gplus_id') if stored_access_token is not None and gplus_id == stored_gplus_id: response = make_response(json.dumps('Current user is' 'already connected.'), 200) response.headers['Content-Type'] = 'application/json' return response # Store the access token in the session for later use. login_session['access_token'] = credentials.access_token login_session['gplus_id'] = gplus_id # Get user info userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = answer.json() login_session['username'] = data['name'] login_session['picture'] = data['picture'] login_session['email'] = data['email'] login_session['provider'] = 'google' # See if user exists user_id = getUserID(data["email"]) if not user_id: user_id = createUser(login_session) login_session['user_id'] = user_id return "Login Successful"
def get_results(data): url = "http://api.nytimes.com/svc/search/v2/articlesearch.json?q=" + data + "&api-key=16544f21c00fca2a33169b99b96a4668%3A16%3A72957421" data = requests.get(url).json() return jsonify(result="This function would return search results", response=data), 201
stored_gplus_id = login_session.get('gplus_id') if stored_access_token is not None and gplus_id == stored_gplus_id: response = make_response (json.dumps('Current user is already connected.'), 200) response.headers['Content-Type'] = 'application/json' return response # Store the access token in the session for later use. login_session['access_token'] = credentials.access_token login_session['gplus_id'] = gplus_id # Get user info userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = answer.json() login_session['username'] = data['name'] login_session['picture'] = data['picture'] login_session['email'] = data['email'] login_session['provider'] = 'google' # See if user exists user_id = getUserID(data["email"]) if not user_id: user_id = createUser(login_session) login_session['user_id'] = user_id return "Login Successful"
''' SIMPLE WEBSCRAPPER TO SCRAPE THE PRICE OF ALL BOOKS ON SAID URL And writes them/saves to a cvs file to be viwed in a spreadsheet. SIMPLY CHANGE THE ELEMENTS AND VARIABLES TO REVERSE ENGINEER THIS TO WORK AS YOU SEE FIT. ''' from flask import Flask, render_template, request, requests from bs4 import BeautifulSoup from csv import writer # Desired website: response = requests.get('http://books.toscrape.com/') # Declare Beautiful Soup Parser: soup = BeautifulSoup(response.text, 'html.parser') #Declare Prices variavle: prices = soup.find_all( class_="product_price") # find all classes with the name product_price # Save Data to CVS file: with open('NameOfFile.csv', 'w') as csv_file: csv_writer = writer(csv_file) # headers = ['Title', 'Price'] headers = ["header1", "header2"] csv_writer.writerow(headers) # loop through prices content and pinpick desired section/content, then save to CVS file for price in prices: myPrice = price.get_text().replace('\n', '')[:7] csv_writer.writerow([myPrice ]) # writes a row of each data into cvs file
def handle_message(event): text = event.message.text #simplify for receove message sender = event.source.user_id #get user_id gid = event.source.sender_id #get group_id #=====[ LEAVE GROUP OR ROOM ]========== if text == 'bye': if isinstance(event.source, SourceGroup): line_bot_api.reply_message( event.reply_token, TextSendMessage(text='Leaving group')) line_bot_api.leave_group(event.source.group_id) elif isinstance(event.source, SourceRoom): line_bot_api.reply_message( event.reply_token, TextSendMessage(text='Leaving group')) line_bot_api.leave_room(event.source.room_id) else: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="Bot can't leave from 1:1 chat")) #=====[ TEMPLATE MESSAGE ]============= elif text == '/template': buttons_template = TemplateSendMessage( alt_text='template', template=ButtonsTemplate( title='[ TEMPLATE MSG ]', text= 'Tap the Button', actions=[ MessageTemplateAction( label='Culum 1', text='/aditmadzs' ), MessageTemplateAction( label='CULUM 2', text='/aditmadzs' ), MessageTemplateAction( label='CULUM 3', text='/aditmadzs' ) ] ) ) line_bot_api.reply_message(event.reply_token, buttons_template) #=====[ CAROUSEL MESSAGE ]========== elif text == '/carousel': message = TemplateSendMessage( alt_text='OTHER MENU', template=CarouselTemplate( columns=[ CarouselColumn( title='ADD ME', text='Contact Aditmadzs', actions=[ URITemplateAction( label='>TAP HERE<', uri='https://line.me/ti/p/~adit_cmct' ) ] ), CarouselColumn( title='Instagram', text='FIND ME ON INSTAGRAM', actions=[ URITemplateAction( label='>TAP HERE!<', uri='http://line.me/ti/p/~adit_cmct' ) ] ) ] ) ) line_bot_api.reply_message(event.reply_token, message) #=====[ FLEX MESSAGE ]========== elif text == 'flex': bubble = BubbleContainer( direction='ltr', hero=ImageComponent( url='https://lh5.googleusercontent.com/VoOmR6tVRwKEow0HySsJ_UdrQrqrpwUwSzQnGa0yBeqSex-4Osar2w-JohT6yPu4Vl4qchND78aU2c5a5Bhl=w1366-h641-rw', size='full', aspect_ratio='20:13', aspect_mode='cover', action=URIAction(uri='http://line.me/ti/p/~adit_cmct', label='label') ), body=BoxComponent( layout='vertical', contents=[ # title TextComponent(text='Aditmadzs', weight='bold', size='xl'), # review BoxComponent( layout='baseline', margin='md', contents=[ IconComponent(size='sm', url='https://example.com/gold_star.png'), IconComponent(size='sm', url='https://example.com/grey_star.png'), IconComponent(size='sm', url='https://example.com/gold_star.png'), IconComponent(size='sm', url='https://example.com/gold_star.png'), IconComponent(size='sm', url='https://example.com/grey_star.png'), TextComponent(text='4.0', size='sm', color='#999999', margin='md', flex=0) ] ), # info BoxComponent( layout='vertical', margin='lg', spacing='sm', contents=[ BoxComponent( layout='baseline', spacing='sm', contents=[ TextComponent( text='Place', color='#aaaaaa', size='sm', flex=1 ), TextComponent( text='Tangerang, Indonesia', wrap=True, color='#666666', size='sm', flex=5 ) ], ), BoxComponent( layout='baseline', spacing='sm', contents=[ TextComponent( text='Time', color='#aaaaaa', size='sm', flex=1 ), TextComponent( text="10:00 - 23:00", wrap=True, color='#666666', size='sm', flex=5, ), ], ), ], ) ], ), footer=BoxComponent( layout='vertical', spacing='sm', contents=[ # separator SeparatorComponent(), # websiteAction ButtonComponent( style='link', height='sm', action=URIAction(label='Aditmadzs', uri="https://line.me/ti/p/~adit_cmct") ) ] ), ) message = FlexSendMessage(alt_text="hello", contents=bubble) line_bot_api.reply_message( event.reply_token, message ) #=====[ FLEX MESSAGE ]========== elif text == '!price': sep = text.split(" ") search = sep.replace(sep[0]+" ","") api = requests.get("https://www.romexchange.com/api?item="+search+"&sort_server={}&sort_range={}&exact=false".format(str("sea"), str("week"))) data = api.text data = json.loads(data) bubble = BubbleContainer( direction='ltr', body=BoxComponent( layout='vertical', contents=[ # title TextComponent(text='Aditmadzs', weight='bold', size='xl'), # review BoxComponent( layout='baseline', margin='md', contents=[ IconComponent(size='sm', url='https://example.com/gold_star.png'), IconComponent(size='sm', url='https://example.com/grey_star.png'), IconComponent(size='sm', url='https://example.com/gold_star.png'), IconComponent(size='sm', url='https://example.com/gold_star.png'), IconComponent(size='sm', url='https://example.com/grey_star.png'), TextComponent(text='4.0', size='sm', color='#999999', margin='md', flex=0) ] ), # info BoxComponent( layout='vertical', margin='lg', spacing='sm', contents=[ for name in data: BoxComponent( layout='baseline', spacing='sm', contents=[ TextComponent( text='SEA', color='#aaaaaa', size='sm', flex=1 ), TextComponent( text= '{}'.format(str(name["name"])), wrap=True, color='#666666', size='sm', flex=5 ) ], ), BoxComponent( layout='baseline', spacing='sm', contents=[ TextComponent( text='Global', color='#aaaaaa', size='sm', flex=1 ), TextComponent( text="10:00 - 23:00", wrap=True, color='#666666', size='sm', flex=5, ), ], ), ], ) ], ), footer=BoxComponent( layout='vertical', spacing='sm', contents=[ # separator SeparatorComponent(), # websiteAction ButtonComponent( style='link', height='sm', action=URIAction(label='Aditmadzs', uri="https://line.me/ti/p/~adit_cmct") ) ] ), ) message = FlexSendMessage(alt_text="hello", contents=bubble) line_bot_api.reply_message( event.reply_token, message )