Python simple web service

Best way to create a simple python web service

From this tutorial: https://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask I’m using this for the server: If I run this from the command line: I get this: Great, now my question is, how can I write a Python script using requests to obtain the same information? I am using bottle library to handle requests to server and create server.

Best way to create a simple python web service

I’ve been using python for years, but I have little experience with python web programming. I’d like to create a very simple web service that exposes some functionality from an existing Python script for use within my company. It will likely return the results in csv. What’s the quickest way to get something up? If it affects your suggestion, I will likely be adding more functionality to this, down the road.

Have a look at werkzeug. Werkzeug started as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility modules. It includes a powerful debugger, full featured request and response objects, HTTP utilities to handle entity tags, cache control headers, HTTP dates, cookie handling, file uploads, a powerful URL routing system and a bunch of community contributed addon modules.

It includes lots of cool tools to work with http and has the advantage that you can use it with wsgi in different environments (cgi, fcgi, apache/mod_wsgi or with a plain simple python server for debugging).

Читайте также:  Self python зачем нужен

web.py is probably the simplest web framework out there. «Bare» CGI is simpler, but you’re completely on your own when it comes to making a service that actually does something.

«Hello, World!» according to web.py isn’t much longer than an bare CGI version, but it adds URL mapping, HTTP command distinction, and query parameter parsing for free :

import web urls = ( '/(.*)', 'hello' ) app = web.application(urls, globals()) class hello: def GET(self, name): if not name: name = 'world' return 'Hello, ' + name + '!' if __name__ == "__main__": app.run() 

The simplest way to get a Python script online is to use CGI:

#!/usr/bin/python print "Content-type: text/html" print print "

Hello world.

"

Put that code in a script that lives in your web server CGI directory, make it executable, and run it. The cgi module has a number of useful utilities when you need to accept parameters from the user.

Raw CGI is kind of a pain, Django is kind of heavyweight. There are a number of simpler, lighter frameworks about, e.g. CherryPy. It’s worth looking around a bit.

Python Socket Programming Simple Web Server, I am working on my first Python socket programming code and I cannot figure out what is wrong. I type in the IP address of the server that this program is running on along with the port number and the file I am trying to receive. I should receive the file in the browser and the socket should close.

How to make a simple Python REST server and client?

I’m attempting to make the simplest possible REST API server and client, with both the server and client being written in Python and running on the same computer.

I’m using this for the server:

# server.py from flask import Flask, jsonify app = Flask(__name__) tasks = [ < 'id': 1, 'title': u'Buy groceries', 'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', 'done': False >, < 'id': 2, 'title': u'Learn Python', 'description': u'Need to find a good Python tutorial on the web', 'done': False >] @app.route('/todo/api/v1.0/tasks', methods=['GET']) def get_tasks(): return jsonify() if __name__ == '__main__': app.run(debug=True) 

If I run this from the command line:

curl -i http://localhost:5000/todo/api/v1.0/tasks 
HTTP/1.0 200 OK Content-Type: application/json Content-Length: 317 Server: Werkzeug/0.16.0 Python/3.6.9 Date: Thu, 05 Mar 2020 02:45:59 GMT < "tasks": [ < "description": "Milk, Cheese, Pizza, Fruit, Tylenol", "done": false, "id": 1, "title": "Buy groceries" >, < "description": "Need to find a good Python tutorial on the web", "done": false, "id": 2, "title": "Learn Python" >] > 

Great, now my question is, how can I write a Python script using requests to obtain the same information?

I suspect this is the proper idea:

# client.py import requests url = 'http://todo/api/v1.0/tasks' response = requests.get(url, # what goes here ?? ) print('response = ' + str(response)) 

However as you can see from my comment, I’m not sure how to set up the parameters for requests.get .

I attempted to use this SO post:

Making a request to a RESTful API using python

as a guideline however it’s not clear how to adjust the formatting per the message change.

Can provide a brief description of how to set up params to pass into requests.get and suggest the necessary changes to get the client example above working? Thanks!

Something else I can mention is that I got the client to work using Postman pretty easily, I’m just not sure how to set up the syntax in Python:

Based on icedwater’s response below, this is complete, working code for the client:

# client.py import requests import json url = 'http://localhost:5000/todo/api/v1.0/tasks' response = requests.get(url) print(str(response)) print('') print(json.dumps(response.json(), indent=4)) 
Help on function get in module requests.api: get(url, params=None, **kwargs) Sends a GET request. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response ` object :rtype: requests.Response 

so I would say requests.get(url) would be enough to get a response. Then look at either the json() or data() functions in response depending on what the API is expected to return.

So for the case of a JSON response, the following code should be enough:

import requests import json url = "https://postman-echo.com/get?testprop=testval" response = requests.get(url) print(json.dumps(response.json(), indent=4)) 

Try the above code with an actual test API.

Web server code in python Code Example, # Creating a Web server using Python and Flask from flask import Flask app = Flask(‘app’) @app.route(‘/’) def run(): return ‘ Hello, Server! ‘ app.run(host = ‘0.0.0.0

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.

Make a python web server Code Example, # Creating a Web server using Python and Flask from flask import Flask app = Flask(‘app’) @app.route(‘/’) def run(): return ‘

Hello, Server!

‘ app.run(host

Источник

Оцените статью