Last active
November 13, 2016 15:25
-
-
Save DEKHTIARJonathan/588fb50153924715b2e820162f009b1f to your computer and use it in GitHub Desktop.
Rapid API Prototyping with Bottle.py - api.py - V3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################## Import Libraries ################## | |
import os.path | |
from bottle import route, run, response, static_file, request, error, Bottle, template | |
from json import dumps, loads, load | |
################## WebService Route / ################## | |
class API: | |
def __init__(self, port, local): | |
self._app = Bottle() | |
self._route() # During initialisation we launch the _route() method to register the routes enabled | |
self._local = local | |
self._port = port | |
if local: | |
self._host = '127.0.0.1' | |
else: | |
self._host = '0.0.0.0' | |
def start(self): | |
self._app.run(server='paste', host=self._host, port=self._port) | |
def _route(self): | |
self._app.hook('before_request')(self._strip_path) # Needed to prevent errors. | |
self._app.route('/', callback=self._homepage) # We tell to the API to listen on "/" and execute the action "_homepage()" when "/" is called | |
# We tell the API to execute _doAction() when a POST Request is perform on "/action" | |
self._app.route('/action', method="POST", callback=self._doAction) | |
# We tell the API to execute _doAction() when a GET Request is perform on "/action" | |
self._app.route('/action', method="GET", callback=self._doAction) | |
def _strip_path(self): | |
request.environ['PATH_INFO'] = request.environ['PATH_INFO'].rstrip('/') | |
def _homepage(self): | |
return static_file("index.html", root=os.getcwd()+'\\html') # We return the "index.html" file as a static file. | |
def _doAction(self): | |
rv = {"status": "Success"} # We create a dictionary with the key "status" = "success" | |
response.content_type = 'application/json' # we set the correct "response.content_type" to "json" format, because "json" is nice and cool ! | |
return dumps(rv) # We dump the dictionary into json file and return it. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment