Skip to main content

Sending request using request library

Using request library for Pirates

 Few years ago using urllib2 was a simplest way for sending and receiving  HTTP Request. But now I'm using  Request library . This  is more simple and powerful. Unfortunately Request is not include in default install and Pip  should be used . 


 Procedure is really simple  and near to standard :

MacBook-Pro-Hohlov:pirates skhohlov$ virtualenv ./env
New python executable in ./env/bin/python2.7
Also creating executable in ./env/bin/python
Installing setuptools, pip, wheel...done.
MacBook-Pro-Hohlov:pirates skhohlov$ source ./env/bin/activate
(env)MacBook-Pro-Hohlov:pirates skhohlov$ 
(env)MacBook-Pro-Hohlov:pirates skhohlov$ 
(env)MacBook-Pro-Hohlov:pirates skhohlov$ pip install requests
Collecting requests
  Using cached requests-2.13.0-py2.py3-none-any.whl
Installing collected packages: requests
Successfully installed requests-2.13.0
You are using pip version 7.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

Few lines of code. 

 Request has a good documentation at :   It will be nice to check it if you have any misunderstanding.   Lets back to pirates game.  One of the first request is three  requests for selecting  correct segment for playing. List   is a powerful and very important  feature of the python  language.  If you  have worked  with C or C++  you should  know  how  much time requires understanding of pointers and correct using. Python  is doing this in  light and easy to understand way. Good tutorial  is here :    
I've created a function  hot to send requests and select proper segment for  future requests: 

def detectdefaultsegment(gamesession, config):
    """ function for detecting default user segment"""
    BaseSegmentURLList = [
    gamesession.headers.update({'sign-code':config['sign-code'], 'server-method':'GetTouch','client-ver':config['client-ver']})
    for  BUrl in BaseSegmentURLList:       ,data="[\""+config['userid']+"\"]")
        if answer.text[0] is not '!':
            segmenturl = BUrl
    return segmenturl

How its works ?
 Lines  3-6 are  our python list  of the  url.
 Line 8 is adding some header to the request  such as client version , sever method etc.
 Lines 9-12 are python loop:  request is send to each url .  Correct answer is started from  digits (timestamp),  incorrect is started from symbol "!".  Correct URL is returned.
All script code are placed at : 

Looks like I will write only SignIn function. Other part is not interested for me.

Generating Signature and Sign in function. 

Article about  swf working with swf shows how to application "crypting" request  again bad guys. 

def generateSignature(jsonstring, servercommand,config ):
    """Generate checksum for sign-code header.
    Each POST request has this one."""
    matrix_string = "The Matrix has you..."    
    return hashlib.md5((matrix_string+jsonstring+servercommand+config['userid']+config['authkey']).encode('ascii')).hexdigest()

and our first  Sign in function  is look like :

def SignIn(gamesession, config, mainurl):
   """ function for SignIn. This not auth function,
   this function is used for marking for setting up flag
   for first signing in per day. """        
   JSON_STRING = """{"s":{"x":null,"gr":null,"l":"en-US","I'm":false,"s":null,"tg":0,"m":"myemail","ar":null,"de":null,"t":0,"a":false,"n":"nickname","vk":{"b":false},"u":"//","i":"pp24685509","fl":false,"np":false,"p":null,"d":"nickname;null;null;en_US;0;;","tip":null},"mr":"","l":"","i":"0","f":[""],"c":{"ht":"Portal","put":null,"i":1,"v":"1.0"},"t":-180,"rr":""}"""
   parsed_string = json.loads(JSON_STRING)
   print("email:{c[m]}, username:{c[n]}, userid:{c[i]}".format(c=parsed_string["s"]))
   print json.dumps(parsed_string)
   sign =  generateSignature(JSON_STRING, 'SignIn', config)
   gamesession.headers.update({'sign-code':sign, 'server-method':'SignIn','client-ver':config['client-ver'], 'signin-authSeed':config['authSeed'], 'signin-authKey':config['authkey'], 'signin-userId':config['userid']})
   answer =,data=JSON_STRING)
   return answer

Main problem is understanding a string "JSON_STRING".  I've sorted out that this string contains nickname , email, link to photo etc.   Everyone  can get this string from  checking headers procedure, I've informed about this one or two weeks ago. Strings #6-8 print  this information.  Those string have debuging purpose only.  Strings #10-12 are preparing request  and sending it to server.
Other server command requires a similar job to our SignIn  function.
I have no interest for this and  I would like to do something  funny and smart  (Ex: Arduino or AI )


Popular posts from this blog

Upgrade postgres 9.4 to 9.6 at Debian linux

I'm using virtual server based on Debian Linux for some my free projects.  One of them is based on Postgres with PostGIS extension.   This windy rainy day is a good time for executing some upgrade. Also I would like to add partman extension for partituoning.
Checking new version. Update package list :
aptitude update Get: 1 jessie-updates InRelease [145 kB] Get: 2 stretch/updates InRelease [62.9 kB] Get: 3 jessie/updates InRelease [63.1 kB]
 Check for new version:

dpkg-query -l postgresql* Desired=Unknown/Install/Remove/Purge/Hold| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)||/ Name Version Ar…

Postfix can not start via systemd (simple fix)

Solving problem related to systemd process I like postfix.   This is really smart and secure mail server. I'm helping above  dozen clients around the world and  tunning  postfix is really fun task. This morning I was downgrading postfix  to the stable version for one of the my friends and come across interesting issue. 
root@newserver:/etc/init.d# systemctl status postfix ● postfix.service Loaded: masked (/dev/null; bad) Active: inactive (dead) since вт 2017-06-13 14:35:41 EEST; 1h 48min ago Main PID: 25145 (code=exited, status=0/SUCCESS)чер 13 14:47:09 newserver systemd[1]: Stopped postfix.service.чер 13 14:47:29 newserver systemd[1]: Stopped postfix.service.чер 13 14:58:22 newserver systemd[1]: Stopped postfix.service.чер 13 14:58:23 newserver systemd[1]: Stopped postfix.service.чер 13 15:05:20 newserver systemd[1]: Stopped postfix.service.чер 13 15:29:06 newserver systemd[1]: Stopped postfix.service.чер 13 15:29:06 newserver systemd[1]: Stopped postfix.service.чер 13 15:…

Small script for one of the plarium game

few notes about google games.
Goggle informed that access to the all games be closed after June, 30. I played "Pirates: Tides of fortune" and decided to limit my game time using small script. Detail is below.
Some history
First internet games were updated network games only. 15 years ago internet connection requires a lot of money and nobody had a problem with lagging of the other players. Usually games uses personal communication protocol. Warbirds, Aces High and Eve online use this way.
Next part use a browser and trivial HTTP protocol. One of the popular game in this area is travian . Travian player uses browser and every browser (PC, cell phone, tablet) can be used for playing. Of course, popularity of the game is related to graphics. Trivial HTTP does not have good power in this and other technology is used for this side. One of them is Flash . Unfortunately flash requires a lot of CPU : "Pirates" was near to froze at my old celeron with 512M…