Forum > Networking and Web Programming

Translation from Python to Lazarus

(1/4) > >>

mpknap:
I have a request. The following code sends the file to the server. The main project is in Python, I do not know this programming environment. I do not know JSON. Anyone can write this in Lazarus Pascal for windows?




--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---import_ requestsimport_ jsonimport_ timeimport_ base64import_ urllib3 urllib3.disable_warnings()picture = open('test4.png', 'rb') # read picturepicture_read = picture.read()base64_picture = base64.b64encode(picture_read) # save picture as  base 64print(len((str(base64_picture)[2:]))) # cutting off the first two characters from byte encoding, you may not need tolinux_time = time.time()linux_time_millisecund = [item for item in str(linux_time) if item != '.'] # formatting time according to the linux era # Below you have two variables in the form of a dictionary, which are protocols for logging in and sending data, this is what I sent youearlier and comes from the creed page (with minor changes) # data in the login in addition to the password and e-mail are free, if you registered a cell phone it will match. login = {'app_version': '1', 'device_model': 'zero', 'device_type': 'raspberry','system_version': 'raspbian','device_id': 'raspberry','password': 'hasÅ‚o', "email": "email"}  # in detection the data in addition to frame content and timestamp are also arbitrary, remember to limit the linux time to 13 characters as on the server,otherwise you will have problems with the date. detection = {"detections": [{"frame_content": '%s'% (str(base64_picture)[2:]), "timestamp": int(''.join(linux_time_millisecund)[:-4]), "latitude": 51.708491,"longitude": 19.476362, "altitude": 12, "accuracy": 1, "provider": 'google map', "width": 45, "height": 45, "id": 1}],"device_id": "raspberry", "androidVersion": 'none', "device_model": "zero", "app_version": '1',"system_version": 'raspbian', "device_type": 'raspberry'} # Once I've created variables, I save them in the json format. with open("login.json", "w") as login_file:    json.dump(login, login_file)with open("login.json", "r") as read_login:    data_login = json.load(read_login) with open("detection.json", "w") as detection_file:    json.dump(detection, detection_file)with open("detection.json", "r") as read_detection:    data_detetion = json.load(read_detection) #request login is to get the authentication token needed to send the image to the server request_login = requests.post('https://api.credo.science/api/v2/user/login', verify=False, json=data_login)print(request_login.status_code, request_login.reason)token = request_login.json()['token'] #in request detection you are sending a json file and a token code, and that's all, the file is on the server request_detection = requests.post('https://api.credo.science/api/v2/detection', verify=False,                                  json=data_detetion, headers={'Authorization': 'Token %s' % token})print(request_detection.status_code, request_detection.reason)print(request_detection.content) 

sash:

--- Quote from: mpknap on July 18, 2018, 07:24:26 am ---I do not know this programming environment. I do not know JSON. Anyone can write this ...

--- End quote ---

Shouldn't it be posted in "jobs" then?

mpknap:
it's not a job offer, it's a free project ;) I do not expect a ready solution (but it would be nice), I'm asking for tips, advice, whatever. I do not know how to start and whether it is possible to translate at all ...

sash:

--- Quote ---I do not know how to start
--- End quote ---

Well, then learn basics about JSON, HTTP APIs, Base64 encoding, then basic Python syntax, and you'll be able to translate it for yourself.

I don't know Python either, but given code has comments, and as I can see, it uses some HTTP API (and API provider's address - so you can check their documentation).

Maybe you won't ever need a Python knowledge, if you know exact task, with their protocol description, you will be able to recreate Pascal code from scratch, with some tweaking and debugging.

engkin:
To read the picture:

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---uses Classes... var  picture: TFileStream;  picture_read: array of byte;...  picture := TFileStream.Create('test4.png',fmOpenRead or fmShareDenyNone);  try    SetLength(picture_read, picture.Size);    picture.Read(picture_read[1], Length(picture_read));  finally    picture.Free;  end;
To convert the read picture to base64:

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---uses base64... var  b64: TBase64EncodingStream;  base64_picture: TStringStream;  picture_read: array of byte;...  base64_picture := TStringStream.Create('');  try    b64 := TBase64EncodingStream.Create(base64_picture);    try      b64.write(picture_read[1], Length(picture_read));    finally      b64.Free;    end; //Do whatever with the result    WriteLn(base64_picture.DataString);//*************   finally    base64_picture.Free;  end;
To generate JSON in accordance with their specs:

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---uses fpjson, ....var   O : TJSONObject;   O := TJSONObject.Create([       'body',       TJSONObject.Create([       'detection',       TJSONObject.Create([                           'accuracy',1.0,                           'altitude',1.0,                           'frame_content',base64_picture.DataString                              //add the rest here//}                            ]),//detection        'device_info',       TJSONObject.Create([                           'adnroidVersion','7.0',                           'deviceId','device Id',                           'deviceModel','device model'                           ]),//device_info        'user_info',       TJSONObject.Create([                           'email','user@email.com',                           'key','access_key'                           ])//user_info                          ]),//body       'header',       TJSONObject.Create([                           'application','1.3',                           'frame_type','detection',                           'protocol','1.0',                           'time_stamp',1518707872                           ])//header                         ]);//root   //See the result  Writeln(O.FormatJSon);  //**********
There is a better way to generate the JSON using classes. Take a look at Laz1.8.2\fpc\3.0.4\source\packages\fcl-json\examples specifically demortti.pp

Navigation

[0] Message Index

[#] Next page

Go to full version