本文整理汇总了Python中request.request函数的典型用法代码示例。如果您正苦于以下问题:Python request函数的具体用法?Python request怎么用?Python request使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了request函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __LoadUserOrders__
def __LoadUserOrders__(self, cur, skchecked=False):
#
# __LoadUserOrders__ : download user all orders for a specific currency
#
# Orders are in the variable User.Book.Orders[$currency$]
#
self.Return=None
if self.Trading:
if not(skchecked):
result=request(self.Session, 'get', MCXNOW_DOMAIN+MCXNOW_ACTION["useraccount"])
if result==0:
return MCXNOW_ERROR['HTTP Error']
else:
texthtml=result.text
if self.__CheckSecretKey__(texthtml):
skOk=True
else:
skOk=False
else:
skOk=True
if skOk:
if cur in MCXNOW_TRADEDCURRENCY:
result=request(self.Session, 'get', MCXNOW_DOMAIN+MCXNOW_ACTION["info"]+"cur="+cur)
if result==0:
return MCXNOW_ERROR['HTTP Error']
else:
textxml=result.text
if ('<orders>')in textxml:
orderslist=textxml.split('<orders>')[1].split('</orders>')[0]
orders=orderslist.split('<o>')
self.User.Book.ClearCurrencyAllOrders(cur)
for i in range(1,len(orders)):
order_id=int(orders[i].split('<id>')[1].split('</id>')[0])
order_confirm=int(orders[i].split('<e>')[1].split('</e>')[0])
order_time=int(orders[i].split('<t>')[1].split('</t>')[0])#time.strftime("%a, %d %b %Y %H:%M:%S",time.localtime(float(orders[i].split('<t>')[1].split('</t>')[0])))
order_type=int(orders[i].split('<b>')[1].split('</b>')[0])
order_amount=float(orders[i].split('<a1>')[1].split('</a1>')[0])
order_price=float(orders[i].split('<p>')[1].split('</p>')[0])
self.User.Book.AddOrder(cur, order_id, order_type,order_time, order_confirm, order_amount, order_price)
else:
return MCXNOW_ERROR['HTTP Error']
if ('<base_bal>')in textxml:
base_bal=float(textxml.split('<base_bal>')[1].split('</base_bal>')[0])
self.User.Book.AddBaseBalance(cur, base_bal)
else:
return MCXNOW_ERROR['HTTP Error']
if ('<cur_bal>')in textxml:
cur_bal=float(textxml.split('<cur_bal>')[1].split('</cur_bal>')[0])
self.User.Book.AddCurrencyBalance(cur, cur_bal)
else:
return MCXNOW_ERROR['HTTP Error']
self.Return=self.User.Book.Orders[cur]
return MCXNOW_ERROR['Ok']
else:
return MCXNOW_ERROR['Unknown Currency']
else:
self.Trading=False
return MCXNOW_ERROR['Session ended']
else:
return MCXNOW_ERROR['Anonymous connexion']
开发者ID:mbuech,项目名称:mcxnowapi,代码行数:60,代码来源:api.py
示例2: get_response
def get_response(self, resource, query_string):
"""
GET a response from a resource.
Arguments:
resource: string resource to GET.
query_string: string query-string.
Returns: tuple (dict request() response, dict json_response content).
"""
response = request('GET', resource, query_string)
is_404 = lambda: '404 Not Found' == response['http_status']
for i in range(50):
if not is_404():
break
time.sleep(1)
response = request('GET', resource, query_string)
if is_404():
self.fail('Response was 404 Not Found for GET ' + resource + \
'?' + query_string)
return response, json.loads(response['content'].decode())
开发者ID:samalba,项目名称:image-spider,代码行数:29,代码来源:Get.py
示例3: test_content
def test_content(self):
self.get.wait_for_passing_content('/status', self.query_string,
self._mk_response_test(['Aborted']))
# Test that total results do not increase over 3 seconds.
response = request('GET', '/result', self.query_string)
json_response = json.loads(response['content'].decode())
len0 = len(json_response)
time.sleep(3)
response = request('GET', '/result', self.query_string)
json_response = json.loads(response['content'].decode())
len1 = len(json_response)
self.assertEqual(len0, len1)
开发者ID:samalba,项目名称:image-spider,代码行数:13,代码来源:Stop.py
示例4: __SendChatMsg__
def __SendChatMsg__(self, msg, skchecked=False):
#
# __SendChatMsg__ : Send a message $msg$ to chat
#
self.Return=None
if self.Trading:
if not(skchecked):
result=request(self.Session, 'get', MCXNOW_DOMAIN+MCXNOW_ACTION["useraccount"])
if result==0:
return MCXNOW_ERROR['HTTP Error']
else:
texthtml=result.text
if self.__CheckSecretKey__(texthtml):
skOk=True
else:
skOk=False
else:
skOk=True
if skOk:
self.Session.get(MCXNOW_DOMAIN+MCXNOW_ACTION["sendchat"]+"&sk="+self.User.SecretKey+"&t="+str(msg))
return MCXNOW_ERROR['Ok']
else:
self.Trading=False
return MCXNOW_ERROR['Session ended']
else:
return MCXNOW_ERROR['Anonymous connexion']
开发者ID:mbuech,项目名称:mcxnowapi,代码行数:26,代码来源:api.py
示例5: __LoadUserDetails__
def __LoadUserDetails__(self):
#
# __LoadUserDetails__ : download all info about user account
#
# Account Info are in the variable User.Details
#
self.Return=None
if self.Trading:
result=request(self.Session, 'get', MCXNOW_DOMAIN+MCXNOW_ACTION["useraccount"])
if result==0:
return MCXNOW_ERROR['HTTP Error']
else:
texthtml=result.text.encode('utf-8')
if self.__CheckSecretKey__(texthtml):
for cur in MCXNOW_ALLCURRENCY:
if cur == 'PPC':
self.User.Details.Funds[cur].Balance=float(texthtml\
.split("PPC</tla><balavail>")[1].split("</baltotal><btctotal>")[0].split("<")[0])
elif cur == 'BTC':
self.User.Details.Funds[cur].Balance=float(texthtml\
.split("PPC</tla><balavail>")[1].split("</baltotal><btctotal>")[0].split("<")[0])
self.User.Details.Funds[cur].DepositAddress=''
self.User.Details.Funds[cur].MinimumDeposit=0.0
self.User.Details.Funds[cur].WithdrawFee=0.0
self.User.Details.Funds[cur].DepositConfirmations=0.0
self.User.Details.Funds[cur].Incoming=0.0
self.Return=self.User.Details
return MCXNOW_ERROR['Ok']
else:
self.Trading=False
return MCXNOW_ERROR['Session ended']
else:
return MCXNOW_ERROR['Anonymous connexion']
开发者ID:mbuech,项目名称:mcxnowapi,代码行数:33,代码来源:api.py
示例6: __init__
def __init__(self, uName):
lg.debug("user::__init__ " +
uName)
self.uName = uName
rTxtOverview = 'user/'+uName+'/overview/'
self.rOverview = request(rTxtOverview)
开发者ID:pabloxxl,项目名称:revi,代码行数:7,代码来源:user.py
示例7: run
def run():
database = get_connection(DATABASE_HOST, DATABASE_PORT, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME)
insert_values = []
response = request(API_URL_CHAMPIONS, 'global')
champions_dict = response['data']
version = response['version']
for champion in champions_dict.values():
insert_values.append(u"({}, {}, {}, {}, {})".format(
champion['id'],
database.escape(champion['name']),
database.escape('http://ddragon.leagueoflegends.com/cdn/{}/img/champion/{}'.format(version, champion['image']['full'])),
database.escape('http://ddragon.leagueoflegends.com/cdn/img/champion/loading/' + champion['image']['full'].replace('.png', '_0.jpg')),
database.escape('http://ddragon.leagueoflegends.com/cdn/img/champion/splash/' + champion['image']['full'].replace('.png', '_0.jpg')),
))
insert_query = u'''
INSERT INTO champions
(id, name, image_icon_url, image_loading_url, image_splash_url)
VALUES
{}
'''.format(u','.join(insert_values))
database.execute('TRUNCATE TABLE champions')
database.execute(insert_query)
开发者ID:winston-wolf,项目名称:lol-master-ease,代码行数:26,代码来源:inject_champions.py
示例8: SendBuyOrder
def SendBuyOrder(self, cur=None, amt=0, price=0 , confirm=0):
#
# SendBuyOrder : send a buy order
# Return 1 if success or 0 if error
#
# if return 0 then self.ErrorCode give you the errorcode !
# if confirm=0:
# self.Return=[$id$,1,$time$,$amt$,$price$]
# else :
# self.Return=[None,1,$time$,$amt$,$price$] (because this order can be executed yet)
# #
if self.Trading:
result=request(self.Session, 'get', MCXNOW_DOMAIN+MCXNOW_ACTION["useraccount"])
if result==0:
self.ErrorCode=MCXNOW_ERROR['HTTP Error']
return 0
else:
texthtml=result.text
if self.__CheckSecretKey__(texthtml):
self.ErrorCode=self.__SendAOrder__(cur, 1, amt, price, confirm, True)
if self.ErrorCode==1:
return 1
else:
return 0
else:
self.ErrorCode=MCXNOW_ERROR['Session ended']
return 0
else:
self.ErrorCode=MCXNOW_ERROR['Anonymous connexion']
return 0
开发者ID:mbuech,项目名称:mcxnowapi,代码行数:31,代码来源:api.py
示例9: __LoadChat__
def __LoadChat__(self):
#
# __LoadChat__ : download all chat
#
# All Message are in the liste Public.Chat
#
self.Return=None
result=request(self.Session, 'get', MCXNOW_DOMAIN+MCXNOW_ACTION["chat"])
if result==0:
return MCXNOW_ERROR['HTTP Error']
else:
textxml=result.text
if '<doc>' in textxml:
# Messages
self.Public.Chat.ClearChat()
messages=textxml.split('<c>')
for i in range(1, len(messages)):
message_user=messages[i].split('<n>')[1].split('</n>')[0]
message_id=messages[i].split('<i>')[1].split('</i>')[0]
message_text=messages[i].split('<t>')[1].split('</t>')[0]
self.Public.Chat.AddMessage(message_id, message_user, message_text)
self.Return=self.Public
return MCXNOW_ERROR['Ok']
else:
return MCXNOW_ERROR['Unknown']
开发者ID:mbuech,项目名称:mcxnowapi,代码行数:25,代码来源:api.py
示例10: search
def search(x,y):
global t
global aux
global m
for i in range(0, 4):
cx, cy = xoy[i]
newx = x + cx
newy = y + cy
if (newx > 0) and (newx < 11) and (newy > 0) and (newy < 11) and ((newx, newy) not in lovit):
print(newx,newy)
lovit.append((newx, newy))
e=request.request(newx,newy)
if e=="HIT":
t+=1
m+=1
hit(newx, newy)
search(newx, newy)
elif e=="DESTROYED":
t+=1
print('DESTROYED')
hit(newx, newy)
return
开发者ID:PlatonV,项目名称:Battleships,代码行数:26,代码来源:hit3_incercare.py
示例11: __init__
def __init__(self, rLink, rType=sortType.HOT, rLimit=25):
rTypeTxt = typeStr(rType)
lg.debug("comments::__init__ " +
rLink + "" +
rTypeTxt + " " +
str(rLimit))
# TODO strip rlink to show in history
self.rLink = rLink
self.rType = rType
self.currComment = 0
rLimitTxt = None
if rLimit is not 25:
rLimitTxt = "limit="+str(rLimit)
params = rLimitTxt
self.r = request(rLink, params)
self.ok = self.r.ok
self.status = self.r.status
if self.ok:
self.json = self.r.json
self.__fetchComments__()
开发者ID:pabloxxl,项目名称:revi,代码行数:27,代码来源:comments.py
示例12: __init__
def __init__(self, rName, rType=sortType.HOT, rLimit=25):
rTypeTxt = typeStr(rType)
lg.debug("listing::__init__ " + rTypeTxt + " " + str(rLimit))
self.rName = rName
self.rType = rType
if self.rName == "":
self.rName = "front"
self.currLine = 0
rLimitTxt = None
if rLimit is not 25:
rLimitTxt = "limit=" + str(rLimit)
# TODO add other options
if rName is "":
rTxt = "/"
else:
rTxt = "/r/" + rName + "/" + rTypeTxt + "/"
params = rLimitTxt
# add other options to params
self.r = request(rTxt, params)
# I should check if request went well
self.ok = self.r.ok
self.status = self.r.status
if self.ok:
self.json = self.r.json
self.__fetchLinks__()
开发者ID:pabloxxl,项目名称:revi,代码行数:32,代码来源:listing.py
示例13: api_pull_match_history
def api_pull_match_history(region, summoner, begin_index):
database = get_connection(DATABASE_HOST, DATABASE_PORT, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME)
# always try getting 15 matches (max) at a time
end_index = begin_index + 15
# fetch matches from the api
logger.warning('[api_pull_match_history] adding request for match history of {}'.format(summoner['id']))
response = request(API_URL_MATCH_LIST, region, summonerId=summoner['id'], beginIndex=begin_index, endIndex=end_index)
if response:
logger.warning('[api_pull_match_history] got {} matches: [{}]'.format(len(response.get('matches', [])), [str(match['matchId']) for match in response.get('matches', [])]))
matches = response.get('matches', [])
if matches:
# see which matches we already have recorded
sql = u"""
SELECT
match_id
FROM
matches
WHERE 1
AND match_region = {region}
AND summoner_id = {summoner_id}
AND match_id IN ({match_ids})
{missing_item_temp_fix_sql}
""".format(
region=database.escape(region),
summoner_id=summoner['id'],
match_ids=','.join(str(match['matchId']) for match in matches),
missing_item_temp_fix_sql=MISSING_ITEM_TEMP_FIX_SQL,
)
recorded_match_ids = database.fetch_all_value(sql)
logger.warning('[api_pull_match_history] sql: {}'.format(sql))
logger.warning('[api_pull_match_history] recorded match ids: {}'.format(recorded_match_ids))
match_stats = []
for match in matches:
# if the match is not already recorded and in this season, then record it
if match['matchId'] not in recorded_match_ids and match['season'] == SEASON_NAME:
logger.warning('[api_pull_match_history] getting stats for match {}'.format(match['matchId']))
thread = SimpleThread(match_helper.get_stats, matchId=match['matchId'], region=region, detailed=False)
match_stats.append(thread)
if match_stats:
match_stats = [stats.result() for stats in match_stats]
logger.warning('[api_pull_match_history] doing player_helper.get_stats()')
player_stats = player_helper.get_stats(match_stats, database)
logger.warning('[api_pull_match_history] inserting player {}'.format(summoner['id']))
player_helper.insert(player_stats, database, summoner['id'])
for match_stat in match_stats:
try:
logger.warning('[api_pull_match_history] inserting match stats for match {}'.format(match_stat['match']['id']))
match_helper.insert(match_stat, player_stats, database, detailed=False)
except Exception, e:
logger.warning('[api_pull_match_history] FAILED inserting match stats for match {}: {}'.format(match_stat['match']['id'], e))
pass
开发者ID:winston-wolf,项目名称:lol-master-ease,代码行数:59,代码来源:views.py
示例14: validate
def validate(input):
if (len(input) == 3):
# covers location, time scenario
#print "length 2"
destination = input[1].title()
time = input[2]
if (locations.valid_location(destination) and
day.valid_time(time)): #valid location
#print "valid location"
req = request.request(destination, time)
return req
elif(len(input) == 4):
# covers location, day, time scenario
print "length 3"
destination = input[1].title()
time = input[3]
day_specified = input[2].title()
if (locations.valid_location(destination)): #valid location
print "valid location"
if (day.valid_time(time)):
print "valid time"
if (day.valid_day(day_specified)):
print "valid day"
req = request.request(destination, time)
day_of_week = day.get_specified(day_of_week)
today = day.get_day(datetime.datetime.today().weekday())
if (today != day_of_week):
req.set_future()
# set n days from
return req
elif(day.valid_specifier(day_specified)):
print "valid day specifier"
req = request.request(destination, time)
return req
# check valid day
# check valid time
elif(len(input) > 4):
# covers location, n days from, time
print "length > 3"
destination = input[1].title()
if (locations.valid_location(destination)): #valid location
print "valid location"
# check valid n days from
# check valid time
开发者ID:Mattw46,项目名称:CPT223-A2-Stage1,代码行数:45,代码来源:validator.py
示例15: ok
def ok(x,y):
global t
t+=1
lovit.append((x, y))
if request.request(x,y) in ["HIT", "DESTROYED"]:
return True
else:
return False
开发者ID:PlatonV,项目名称:Battleships,代码行数:8,代码来源:main.py
示例16: __init__
def __init__(self):
super().__init__()
self.db = db();
self.req = request()
self.hosts_file = "/etc/hosts"
return
开发者ID:dvjs,项目名称:hosts,代码行数:8,代码来源:command.py
示例17: __Login__
def __Login__(self):
self.Return=None
logindata={'user': self.User.UserName, 'pass': self.User.Password}
result=request(self.Session, 'post', MCXNOW_DOMAIN+MCXNOW_ACTION["login"], data=logindata)
if result==0:
return MCXNOW_ERROR['HTTP Error']
else:
if result.status_code==200:
result=request(self.Session, 'get', MCXNOW_DOMAIN+MCXNOW_ACTION["useraccount"])
texthtml=result.text
if 'sk' in texthtml :
self.User.SecretKey=texthtml.split('sk=')[1].split("'")[0]
self.Trading=True
return MCXNOW_ERROR['Ok']
else :
return MCXNOW_ERROR['Unknown']
else:
return MCXNOW_ERROR['HTTP Error']
开发者ID:mbuech,项目名称:mcxnowapi,代码行数:18,代码来源:api.py
示例18: wiki
def wiki(term):
resp = json.loads(request('http://en.wikipedia.org/w/api.php/', data={
'action' : 'opensearch',
'search' : term,
'limit' : 1,
'format' : 'json'
}).read().decode())
print("{title} : {description}".format(title=resp[1][0], description=resp[2][0]))
print("Read more at {link}".format(link=resp[3][0]))
开发者ID:carriercomm,项目名称:KA,代码行数:9,代码来源:wiki.py
示例19: search
def search(x,y):
print("Am pornit")
print(x,y)
for i in range(0,4):
m,n=xoy[i]
if(x+m<11)&(y+n<11)&(x+m>-1)&(y+n>-1):
lovit.append((x, y))
if (request.request(chr(x+m-1+ord('A')),y+n+1)in["HIT","DESTROYED"]) & ((x+m,y+n) not in lovit):
search(x+m,y+n)
hit(m+x,n+y)
开发者ID:PlatonV,项目名称:Battleships,代码行数:10,代码来源:hit.py
示例20: hit
def hit(x,y):
print("Am pornit")
print(x,y)
if (s[x-1][y-1]=="1") :
print("lovit")
for i in range(0,4):
m,n=xoy[i]
if(x+m<11)&(y+n<11)&(x+m>-1)&(y+n>-1):
if (request.request(chr(x+m-1+ord('A')),y+n+1)in["HIT","DESTROYED"]) & ((x+m,y+n) not in lovit):
hit(x+m,y+n)
lovit.append((m+x,n+y))
开发者ID:PlatonV,项目名称:Battleships,代码行数:11,代码来源:hit.py
注:本文中的request.request函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论