def _sell(API_Token, APISecret, Market, Balance): """ This will post a "MARKET" order, which should be immediately filled at whatever market rate is. """ data = { "marketSymbol": Market["MarketName"], "direction": "SELL", "type": "MARKET", "quantity": Balance, "timeInForce": "FILL_OR_KILL", } ts = arrow.now().timestamp * 1000 # Transforms ts from seconds into milliseconds uri = "https://api.bittrex.com/v3/orders" contentHash, signature = generateAuth(API_Token, APISecret, ts, str(data), uri, "POST") headers = { "Api-Key": API_Token, "Api-Timestamp": ts; "Api-Content-Hash": contentHash; "Api-Signature": signature } r = requests.post(uri, data=data, headers=headers) r.raise_for_status() res = r.json() return res["id"]
def _checkOrder(API_Token, APISecret, UUID): """ Returns true/false based on whether an order needs to be retried """ ts = arrow.now().timestamp * 1000 # Transforms ts from seconds into milliseconds uri = "https://api.bittrex.com/v3/orders/%s" % UUID contentHash, signature = generateAuth(API_Token, APISecret, ts, "", uri, "GET") headers = { "Api-Key": API_Token, "Api-Timestamp": ts; "Api-Content-Hash": contentHash; "Api-Signature": signature } r = requests.get(uri, headers=headers) r.raise_for_status() res = r.json() if res["quantity"] != res['fillQuantity']: # Order didn't completely fill; need to signal that the rest should be sold somehow #TODO return True elif res['fillQuantity'] == 0.0: # Order was not filled at all; needs to be reattempted immediately return False else: # Order filled completely #TODO include timestamp and market in this logging message print("Order filled successfully!") return True
def paste(update, context): args = context.args BURL = "https://del.dog" message = update.effective_message if message.reply_to_message: data = message.reply_to_message.text elif len(args) >= 1: data = message.text.split(None, 1)[1] else: message.reply_text("What am I supposed to do with this?!") return r = requests.post(f"{BURL}/documents", data=data.encode("utf-8")) if r.status_code == 404: update.effective_message.reply_text("Failed to reach dogbin") r.raise_for_status() res = r.json() if r.status_code != 200: update.effective_message.reply_text(res["message"]) r.raise_for_status() key = res["key"] if res["isUrl"]: reply = "Shortened URL: {}/{}\nYou can view stats, etc. [here]({}/v/{})".format( BURL, key, BURL, key) else: reply = f"{BURL}/{key}" update.effective_message.reply_text(reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
def Location_Result(): data = [] urls = URL_POSTFIX() for i in urls: url = i['paramus'] try: request = requests.post(url) if request.status_code == 200: time.sleep(.90) json_data = request.json() for item in json_data['results']: data.append(item) createFile('./static/locations.json', data) except ValueError: print requests.raise_for_status() return request
def astronomy(self, zmw): url = "http://api.wunderground.com/api/{}/astronomy/{}.json".format( api_key, zmw) try: response = requests.get(url) except requests.raise_for_status() as err: return(err) try: json_data = json.loads(response.text) return (json_data) except Exception as e: return(e)
def get_paste_content(update, context): args = context.args BURL = 'https://del.dog' message = update.effective_message chat = update.effective_chat # type: Optional[Chat] if len(args) >= 1: key = args[0] else: message.reply_text("Please supply a dogbin url!") return format_normal = f'{BURL}/' format_view = f'{BURL}/v/' if key.startswith(format_view): key = key[len(format_view):] elif key.startswith(format_normal): key = key[len(format_normal):] r = requests.get(f'{BURL}/raw/{key}') if r.status_code != 200: try: res = r.json() update.effective_message.reply_text(res['message']) except Exception: if r.status_code == 404: update.effective_message.reply_text( "Failed to reach dogbin") else: update.effective_message.reply_text( "Unknown error occured") r.raise_for_status() update.effective_message.reply_text('```' + escape_markdown(r.text) + '```', parse_mode=ParseMode.MARKDOWN)
def get_id(self, name): url = "http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key={}&vanityurl={}".format( api_key, name) try: # response = urllib.request.urlopen(url) response = requests.get(url) except requests.raise_for_status() as err: return(err) try: json_data = json.loads(response.text) _str_ = "`{}'s Steam ID is: {}.`".format( name, str(json_data['response']['steamid'])) return (_str_) except Exception as e: return(e)
#! /usr/bin/env python3 import requests, glob, os path = "supplier-data/images" os.chdir(path) pictures = [] pictures = glob.glob("*.jpeg") url = "http://localhost/upload/" for picture in pictures: with open(picture, "r") as opened: requests = requests.post(url, files={'file': opened}) requests.raise_for_status()
如果在刚才的脚本中,我们输入了错误的地址,比如: -------------------------------------------------------------------------------- import requests res = requests.get('http://www.gutenberg.org/cache/epub/hahahahahahhahaha/pg1112.txt') -------------------------------------------------------------------------------- 地址虽然会404,但程序却不会终止,这样很容易后续程序崩溃。 所以我们要防患于未然,如果 requests.get()出现任何问题,我们要马上终止程序并显示错误提示 这里我们只需要用一个简单的方法来完成: requests.raise_for_status() -------------------------------------------------------------------------------- import requests res = requests.get('http://www.gutenberg.org/cache/epub/hahahahahahhahaha/pg1112.txt') res.raise_for_status() -------------------------------------------------------------------------------- 如果你觉得这个错误提示太吓人,你可以用 try except 来自定义一下: -------------------------------------------------------------------------------- import requests res = requests.get('http://www.gutenberg.org/cache/epub/sdfsf/pg1111.txt') try: res.raise_for_status() except Exception as err: print("哦豁!出错了!错误是:{}".format(err)) --------------------------------------------------------------------------------
async def info(self, ctx, *, streamer : str): """Returns information on a streamer.""" sql.log_command(ctx) try: response = requests.get('https://api.twitch.tv/kraken/channels/{}?client_id={}'.format(streamer, cid)) except requests.raise_for_status() as err: await self.bot.say(err) try: await self.bot.send_typing(ctx.message.channel) jst = json.loads(response.text) url = jst['profile_banner'] if jst['profile_banner'] == None: url = 'http://i.imgur.com/psPlXiI.png' url1 = jst['logo'] background = Image.new('RGBA', (1920, 1080), (0, 0, 0, 255)) bg_w, bg_h = background.size response = requests.get(url) banner = Image.open(BytesIO(response.content)) response = requests.get(url1) image = Image.open(BytesIO(response.content)) banner = banner.resize((1920,1080), resample=Image.BICUBIC) banner_w, banner_h = banner.size (int((bg_w - banner_w) / 2), int((bg_h - banner_h) / 2)) banner = banner.rotate(180) banner.putalpha(255) width, height = banner.size pixels = banner.load() for y in range(int(height*.55), int(height*.75)): alpha = 255 - int((y - height*.55)/height/.20 * 255) # print(alpha) for x in range(width): pixels[x, y] = pixels[x, y][:3] + (alpha,) for y in range(y, height): alpha = 255 - int((y - width*.55)/width/.20 * 255) for x in range(width): pixels[x, y] = pixels[x, y][:3] + (0,) pixels[x, y] = (34, 34, 34, alpha) banner = banner.rotate(180) background.paste(banner, (0, 0)) banner = background banner.paste(image, (0,0)) draw = ImageDraw.Draw(banner) font = ImageFont.truetype("cogs/resources/fonts/ComicSans.ttf", 58) try: response = requests.get('https://api.twitch.tv/kraken/streams/{}?client_id={}'.format(streamer, cid)) json_data = json.loads(response.text) status = json_data['stream'] if status != None: draw.ellipse([(1830, 20), (1890, 80)], fill = 'red', outline ='red')#60, 60 timeNow = dateutil.parser.parse(str(datetime.datetime.now(timezone('UTC')).replace(tzinfo=None))) timeThen = dateutil.parser.parse(str(json_data['stream']['created_at'])).replace(tzinfo=None) timeDiff = timeNow - timeThen hours, remainder = divmod(timeDiff.total_seconds(), 3600) minutes, seconds = divmod(remainder, 60) hours = int(hours) minutes = int(minutes) seconds = int(seconds) # x, y = 300, 240 self.backdrop(950, 140, "Started stream: {} {}".format(json_data['stream']['created_at'][0:10],json_data['stream']['created_at'][11:16]) , draw, font) # x, y = 300, 340 self.backdrop(950, 240, "({} hours {} minutes {} seconds)".format(hours, minutes, seconds), draw, font) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] await self.bot.say("`{} {} {}`".format(exc_type, fname, exc_tb.tb_lineno)) status = jst['created_at'] year = status[0:4] month = status[5:7] day = status[8:10] self.backdrop(300, 0, "Currently playing: {}".format(jst['game']), draw, font) self.backdrop(300, 140, "Created at: {}/{}/{}".format(month, day, year), draw, font) self.backdrop(950, 70, "Views: {}".format(jst['views']), draw, font) self.backdrop(300, 70, "Followers: {}".format(jst['followers']), draw, font) banner.paste(image, (0,0)) banner = banner.resize((960,540), resample=Image.BICUBIC) banner.save('temp.png') with open('temp.png', 'rb') as f: await self.bot.upload(f) os.remove('temp.png') except KeyError as e: await self.bot.say("`Error. User probably doesn't exist.`") except Exception as e: await self.bot.say(e)
import requests as req import json url = "http://0.0.0.0:8080/filepath/" print("==================================================================") print("\t\tWelcome to Distributed File System") print("==================================================================\n") print("1. Read File") print("2. Write File") print("3. Delete File\n") options = input("Select the option to:- \n") if options == '1': filepath = input("Enter the file name:") url = url + filepath response = req.get(url) print("Response: ", response.text) if options == '2': filepath = input("Enter the file name:") url = url + filepath data = {'Responcse': 'Hello world'} request = req.post(url, data=data) req.raise_for_status() print("Response: ", response.text) if options == '3': filepath = input("Enter the file name:") url = url + filepath response = req.delete(url) print("File removed")