Simple python json server

Simple Python server to process GET and POST requests with JSON

Solution 1: I recommend using the awesome requests library: JSON Response Content: https://requests.readthedocs.io/en/master/user/quickstart/#json-response-content Solution 2: The Python module takes care of both retrieving JSON data and decoding it, due to its builtin JSON decoder. However, if I send the data directly as it is shown in my first code, due to delays and I am not so sure what else, if i am lucky, full data will be sent, otherwise I keep losing some part of the data fetched.

HTTP requests and JSON parsing in Python

I want to dynamically query Google Maps through the Google Directions API. As an example, this request calculates the route from Chicago, IL to Los Angeles, CA via two waypoints in Joplin, MO and Oklahoma City, OK:

It returns a result in the JSON format.

How can I do this in Python? I want to send such a request, receive the result and parse it.

I recommend using the awesome requests library:

import requests url = '//maps.googleapis.com/maps/api/directions/json' params = dict( origin='Chicago,IL', destination='Los+Angeles,CA', waypoints='Joplin,MO|Oklahoma+City,OK', sensor='false' ) resp = requests.get(url=url, params=params) data = resp.json() # Check the JSON Response Content documentation below 

The requests Python module takes care of both retrieving JSON data and decoding it, due to its builtin JSON decoder. Here is an example taken from the module’s documentation:

>>> import requests >>> r = requests.get('https://github.com/timeline.json') >>> r.json() [ 

So there is no use of having to use some separate module for decoding JSON.

requests has built-in .json() method

import requests requests.get(url).json() 
import urllib import json url = '//maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false' result = json.load(urllib.urlopen(url)) 

HTTP requests and JSON parsing in Python, I want to dynamically query Google Maps through the Google Directions API. As an example, this request calculates the route from Chicago, IL to Los Angeles, CA via two waypoints in Joplin, MO and Code sampleresp = requests.get(url=url, params=params)data = resp.json() # Check the JSON Response Content documentation belowFeedback

Simple Python server to process GET and POST requests with JSON

I'm trying to create a simple Python server in order to test my frontend. It should be able to handle GET and POST requests. The data should be always in JSON format until they are translated to HTTP request/response. A script with corresponding name should be called to handle each request.

#!/usr/bin/env python from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import SocketServer import json import urlparse import subprocess class S(BaseHTTPRequestHandler): def _set_headers(self): self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() def do_GET(self): self._set_headers() parsed_path = urlparse.urlparse(self.path) request_id = parsed_path.path response = subprocess.check_output(["python", request_id]) self.wfile.write(json.dumps(response)) def do_POST(self): self._set_headers() parsed_path = urlparse.urlparse(self.path) request_id = parsed_path.path response = subprocess.check_output(["python", request_id]) self.wfile.write(json.dumps(response)) def do_HEAD(self): self._set_headers() def run(server_class=HTTPServer, handler_class=S, port=8000): server_address = ('', port) httpd = server_class(server_address, handler_class) print 'Starting httpd. ' httpd.serve_forever() if __name__ == "__main__": from sys import argv if len(argv) == 2: run(port=int(argv[1])) else: run() 

Example of testscript.py for handling requests, which in this case just returns a JSON object.

The server should for example return for a response in format http://www.domainname.com:8000/testscript.

My problem is that I can't figure out how to pass variables in between and I need help to make it work.

Here is an example of server client in python. I am using bottle library to handle requests to server and create server.

Server Code

import subprocess from bottle import run, post, request, response, get, route @route('/',method = 'POST') def process(path): return subprocess.check_output(['python',path+'.py'],shell=True) run(host='localhost', port=8080, debug=True) 

It starts server on localhost:8080 . You can pass file name you want to run run. Make sure that file is in the same path for above code to work or change path appropriately to run from different directory. Path corresponds to file name and it invokes process function when any path is given. If it cannot find file it raises exception Internal server error. You can call scripts from subdirectories too.

Client Code

import httplib, subprocess c = httplib.HTTPConnection('localhost', 8080) c.request('POST', '/return', '<>') doc = c.getresponse().read() print doc 

It invokes a POST request to localhost:8080/return

Make sure you print your output response as we are using subprocess.check_output() as it catches only print statements.

Use Popen in subprocess to open a continuous connection instead of check_output to pass arguments to function in server

Check this documentation on how to extract POST or GET values

from apiserve import ApiServer, ApiRoute class MyServer(ApiServer): @ApiRoute("/popup") def addbar(req): return @ApiRoute("/baz") def justret(req): if req: raise ApiError(501,"no data in for baz") return MyServer("127.0.0.1",8000).serve_forever() 

That particular wrapper allows you to easily listen on port 0 (random high port) which some frameworks obfuscate. It automatically handles GET/POST requests for all routes, and it merges in URI arguments with the top level JSON object arguments. Which is good enough for me in most cases.

It's a lot lighter weight than most frameworks. Test cases in the gist show better how it works.

Just one more option for those who prefer Flask . This framework is very popular and quite well documented.

Create file wsgi.py (name is important to not to have a deal with environment variables later) with the content like the following:

from flask import Flask, request app = Flask(__name__) @app.route('/object/') def get_object(path_param): return < 'path_param': path_param, 'query_param': request.args.get('q', "'q' not set"), >if __name__ == '__main__': app.run() 

Run server in terminal like: flask run --reload --host "127.0.0.1" --port 7777

Send queries like: curl -i http://localhost:7777/object/something?q=q

Also don't forget to do pip3 install flask to make this work.

How do I parse a JSON response from Python Requests?

I am trying to parse a response.text that I get when I make a request using the Python Requests library. For example:

def check_user(self): method = 'POST' url = 'http://localhost:5000/login' ck = cookielib.CookieJar() self.response = requests.request(method,url,data='username=test1&passwd=pass1', cookies=ck) print self.response.text 

When I execute this method, the output is:

I would like to check whether "result" equals "success" , ignoring whatever comes before.

The manual suggests: if self.response.status_code == requests.codes.ok:

if json.loads(self.response.text)['result'] == 'success': whatever() 

Since the output, response , appears to be a dictionary, you should be able to do

result = self.response.json().get('result') print(result) 

If the response is in json you could do something like (python3):

import json import requests as reqs # Make the HTTP request. response = reqs.get('http://demo.ckan.org/api/3/action/group_list') # Use the json module to load CKAN's response into a dictionary. response_dict = json.loads(response.text) for i in response_dict: print("key: ", i, "val: ", response_dict[i]) 

To see everything in the response you can use .__dict__ :

 import json def check_user(self): method = 'POST' url = 'http://localhost:5000/login' ck = cookielib.CookieJar() response = requests.request(method,url,data='username=test1&passwd=pass1', cookies=ck) #this line converts the response to a python dict which can then be parsed easily response_native = json.loads(response.text) return self.response_native.get('result') == 'success' 

Python requests api params Code Example, Get code examples like "python requests api params" instantly right from your google search results with the Grepper Chrome Extension. Follow . GREPPER; SEARCH SNIPPETS; PRICING; FAQ; USAGE DOCS ; INSTALL GREPPER; Log In; All Languages >> Python >> python requests api params “python requests api …

GET and POST in JSON using requests in Python

I am working on a project where I have to GET data from a link and then POST the data in another server after I have extracted the information that I needed from the data fetched. I am using the library requests for my GET and POST, and here's the code for extracting the data needed:

 ''' original data fetched result= ,]> ''' for devices in result['devices']: # delete the parameters I don't need final_data = removekey(devices,'model') # x.update(final_data) -> Trying dicts # x.append(final_data) -> Trying lists # Sending directly resp = requests.post(url,json=final_data,headers=headers) no+=1 if no== len(result['devices']): break 

This is where I will call a function that will delete keys that are not needed and then I will take the rest and post it.

and I tried using the update() function for dictionaries but it didn't work due to the fact that I have the same keys so only one of the data will be considered. Lists work but I will get the data in this form:

and I tried to use json=data and x.json() but both didn't work out for lists. However, if I send the data directly as it is shown in my first code, due to delays and I am not so sure what else, if i am lucky, full data will be sent, otherwise I keep losing some part of the data fetched.

How do I GET data in json and then send it back again in json for this case? My aim is to send the data as one bundle, all the devices together so I don't lose anything.

Here are the GET and POST I am using:

 # GET url_source = 'https://website' url = requests.get(url_source) result = url.json() # POST headers = url = "http://xxxx/_get_v1.php" data = final_data resp = requests.post(url,json=data,headers=headers) 

As I commented, devices is not an invalid input(though a valid json). According @AhmedAl-haddad reply, we should send <> -formatted data.

If it means to remove 'model' from devices and send the updated GET response data as below.

# POST headers = url = "http://xxxx/_get_v1.php" # remove 'models' map(lambda x: x.pop('model'), result['devices']) # send result resp = requests.post(url,json=result,headers=headers) 

Or we need to send device in devices separately?

# send result for device in result['devices']: resp = requests.post(url,json=device,headers=headers) 

As @JonDeen mentioned, you should read the document to get more details

Are you asking how to remove a key from a dictionary? If so, use the syntax

Also consider using the json-API for simplicity if you want to manipulate the dataset and restructure it from lists vs. strings.

Also check the Requests documentation for example on submitting json.

Example (updated to remove unnecessary list update):

devices=result['devices'] for i,device in enumerate(devices): # delete the parameters I don't need del device['model'] resp = requests.post(url,json=devices,headers=headers) 

Источник

Читайте также:  Python напечатать элементы массива
Оцените статью