BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Bottle micro web services framework 4 : json

Bottle_Logo.png




Bookmark and Share





bogotobogo.com site search:



List of Bottle Micro Web Services Tutorials

  1. Introduction
  2. Static files
  3. Template
  4. json
  5. Bucket List App I - sqlite, route, and template
  6. Bucket List App II - get & post
  7. Bucket List App III - Editing
  8. Bucket List App IV - route validation, regex, and static_file
  9. Bucket List App V - json
  10. json to html table
  11. Forms - Get & Post
  12. Forms - Get & Post with editable and checkbox table cells



Bottle & json

Don't name a file json.py!




The simplest bottle with json

In this chapter, we'll start from the simplest json:

bjson.py:

from bottle import Bottle, route, run, static_file, template
import time

app = Bottle()

HOST = 'localhost'

@app.route('/api/status')
def api_status():
    return {'status':'online', 'servertime':time.time()}

run(app, host=HOST, port=8080, debug=True)

Run the server:

$ python bjson.py
Bottle v0.12.7 server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.

127.0.0.1 - - [06/Oct/2014 20:08:03] "GET /api/status HTTP/1.1" 200 53

simplest_json.png




Emulating browser with Python's requests and json modules

In this section, we'll write two codes:

  1. req.py : makes a get request and receive two values for the inquiry.
  2. res.py : bottle server, processes the incoming request.

req.py:

import requests
import json

a = 'Hello'
b = 'K'

http = 'http://192.168.47.101:8080/' + a +'/' + b
print http

# get
r = requests.get(http)

print 'r.json().get("time") = %s' %(r.json().get('time'))
print 'r.json().get("g") = %s' %(r.json().get("g"))

res.py:

#!/usr/bin/python
from bottle import Bottle, request, BaseRequest
import datetime

app = Bottle()

@app.get('//')
def notification(greeting, name):
    t = datetime.date.today().ctime()
    gr = greeting + ' ' + name + '!'
    return {'time':t, 'g': gr}

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True)


Now, run the bottle server:

$ python res.py
Bottle v0.12.7 server starting up (using WSGIRefServer())...
Listening on http://0.0.0.0:8080/
Hit Ctrl-C to quit.

Then, make a request:

$ python req.py
http://192.168.47.101:8080/Hello/K
r.json().get("time") = Thu Oct 16 00:00:00 2014
r.json().get("g") = Hello K!

We get the current time and greeting as a response from the bottle!

On the server side, we got the following message:

$ python res.py
Bottle v0.12.7 server starting up (using WSGIRefServer())...
Listening on http://0.0.0.0:8080/
Hit Ctrl-C to quit.

192.168.47.101 - - [16/Oct/3024!!! 06:53:10] "GET /Hello/K HTTP/1.1" 200 53


How about "post" case?

We want to add post coding to both sides:


req.py:

import requests
import json

a = 'Hello'
b = 'K'

http = 'http://192.168.47.101:8080/' + a +'/' + b
print http

# get
# r = requests.get(http)

# post
h = {'content-type': 'application/json'}
res = requests.post(http, headers=h)

print 'res.json().get("time") = %s' %(res.json().get('time'))
print 'res.json().get("g") = %s' %(res.json().get("g"))

print 'res = %s' %(res)

res.py:

#!/usr/bin/python
from bottle import Bottle, request, BaseRequest
import datetime

app = Bottle()

@app.get('//')
def notification(greeting, name):
    t = datetime.date.today().ctime()
    gr = greeting + ' ' + name + '!'
    return {'time':t, 'g': gr}

@app.post('//')
def notification(greeting, name):
    t = datetime.date.today().ctime()
    gr = greeting + ' ' + name + '!'
    return {'time':t, 'g': gr}

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True)


Then, run the server and make a post request:

$ python req.py
http://192.168.47.101:8080/Hello/K
res.json().get("time") = Thu Oct 16 00:00:00 2014
res.json().get("g") = Hello K!
res = 

On the server side, we can see it got post request:

$ python res.py
Bottle v0.12.7 server starting up (using WSGIRefServer())...
Listening on http://0.0.0.0:8080/
Hit Ctrl-C to quit.

192.168.47.101 - - [16/Oct/2014 07:16:05] "POST /Hello/K HTTP/1.1" 200 53



json & filter

Filters are used to define more specific wildcards, and/or transform the covered part of the URL before it is passed to the callback. A filtered wildcard is declared as <name:filter>

In the following example, we simply added a filter for integer type to pass an 'id' for a book. The book() callback takes the id and returns a json with the id and the name of the book:


bjson.py:

from bottle import Bottle, route, run, static_file, template
import time

HOST = 'localhost'

@route('/api/status')
def api_status():
    return {'status':'online', 'servertime':time.time()}

@route('/book/', method='GET')
def book(id):
    return {'id':id, 'name':'The Book Thief'}

run(host=HOST, port=8080, debug=True)


json_filter.png







Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Bottle Micro Web Services Tutorials



Introduction

Static files

Template

json

Bucket List App I - sqlite, route, and template

Bucket List App II - get & post

Bucket List App III - Editing

Bucket List App IV - route validation, regex, and static_file

Bucket List App V - json

json to html table

Forms - Get & Post

Forms - Get & Post with editable and checkbox table cells

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Selenium WebDriver

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master