Cooperation between python module and API

Preface

I tried to link the Python module for Front and the API created by Spring Boot, so I will leave a note of the flow.

The Python module uses a web framework called ** Pyramid **.

Rough flow of the whole

Details

Start Python / SpringBootAPI

Invoke the Python module to receive the request from the browser In order to receive the request from Python, the API is started.

(env) username@host:~/dirname/PythonProject1$ pserve development.ini 
Starting server in PID 6660. 
Serving on http://0.0.0.0:50001

Send HTTP request from browser

Enter the URL below into your browser.

http://0.0.0.0:50001/hotel/

context/view.config

Manage routing here.

When / hotel is accessed, the processing of ** view_hotel_list ** of ** HotelListContext ** is started.

def set_detail_setting(config):

    RootContext.set_child(
        name='hotel',
        factory=HotelListContext,
    )

    config.add_view(
        context=HotelListContext,
        view=context_as_view,
        attr='view_hotel_list',
        renderer='hotel/common/hotel/listHotel.jinja2',
        request_method='GET',
        name=''
    )

context/list/list.py

The process is passed to the Executor, the result is validated and data is processed, and the result is passed.

class HotelListContext(HotelListBaseContext):

    def view_hotel_list(self):
        logger.info('Start search hotel result.')

        list_executor = Executor(self.list_service)
        list_form = self.validated_form(HotelSchema)
        response = list_executor.execute_search_products(list_form.data)
        logger.info(response)
        return {
            'data': {
                'hotels': response['body']['items'],
                'pagination': response['body']['pagination']
            }
        }

context/list/executor/__init__.py

After creating JSON for the request, send the request to the API. Return the response to /context/list/list.py.

class HotelSearchListExecutor(object):

    def __init__(self, service):
        self.service = service

    def execute_search_products(self, condition):
        detail_condition = {
            'header': executor_create_header_request(condition),
            'body': {
                'query': condition.get('query')
                'searchBy': condition.get('searchBy'),
                'pageNum': condition.get('pageNum'),
                'sortBy': condition.get('pageNum'),
                'sortOrder': condition.get('sortOrder')
            }
        }
        return self.service.search_hotel(detail_condition)

listHotel_jinja2

Display JSON passed from /context/list/list.py in jinja2


<!DOCTYPE html>
<html lang=
"en">
<head>
    <title>Test page</title>
</head>
<body>
<table border=1>
    <tr>
        <td>id</td>
        <td>name</td>
        <td>cityCode</td>
    </tr>
    {% for item in data.hotels %}
        <tr>
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.cityCode }}</td>
        </tr>
    {% endfor %}
</table>
</body>
</html>

Methods and definitions used in the flow

development.ini

Define the URL when making a request to the API here

URL = http://localhost:8080/hotel/

executor_helper.py

context/list/executor/__init__.py -> executor_create_header_request(condition)

This is the request header template used in the above process.

def executor_create_header_request(condition):

    return {
        'languageCode': 'en',
        'countryCode': 'US',
        'currencyCode': 'USD'
    }

schema/hotel/__init__.py

/context/list/list.py ⇒ self.validated_form(HotelSchema)

Here, the validate process is performed.

class HotelSchema(Schema):
    allow_extra_fields = True
    filter_extra_fields = True
    query = validators.UnicodeString(not_empty=False, if_missing='')
    sortBy = validators.UnicodeString(not_empty=False, if_missing='name')
    pageNum = validators.UnicodeString(not_empty=False, if_missing='1')
    sortOrder = validators.UnicodeString(not_empty=False, if_missing='ASC')

Results in the browser

20160920155820.png

DB data is displayed on the browser screen through the API.

With this, it was confirmed that the Python module and API could be linked.

Recommended Posts

Cooperation between python module and API
Python debug and test module
Cooperation between py2exe and setuptools
Difference between Ruby and Python split
Difference between java and python (memo)
Difference between list () and [] in Python
Python module num2words Difference in behavior between English and Russian
[Code] Module and Python version output
Differences between Python, stftime and strptime
Difference between python2 series and python3 series dict.keys ()
Python3 socket module and socket communication flow
[Python] Difference between function and method
Python --Difference between exec and eval
[Python] Difference between randrange () and randint ()
[Python] Difference between sorted and sorted (Colaboratory)
Communicate between Elixir and Python with gRPC
Differences in authenticity between Python and JavaScript
Differences between Ruby and Python in scope
difference between statements (statements) and expressions (expressions) in Python
Implementation module "deque" in queue and Python
Create Python module [CarSensor API support module csapi]
Difference between @classmethod and @staticmethod in Python
Difference between append and + = in Python list
Difference between nonlocal and global in Python
[Python] Difference between class method and static method
[Python3] Switch between Shift_JIS, UTF-8 and ASCII
[Python Iroha] Difference between List and Tuple
[python] Difference between rand and randn output
Differences in multithreading between Python and Jython
Differences between Ruby and Python (basic syntax)
Module import and exception handling in python
Correspondence between Python built-in functions and Rust
Exchange encrypted data between Python and C #
Python module import
Python collections module
Summary of the differences between PHP and Python
The answer of "1/2" is different between python2 and 3
[python] Difference between variables and self. Variables in class
About the difference between "==" and "is" in python
Python hand play (interoperability between CSV and PostgreSQL)
Pass values between pages using Python 3.5 cgi module
Get Gmail subject and body with Python and Gmail API
Amazon API Gateway and AWS Lambda Python version
[Python] Class type and usage of datetime module
Try using ChatWork API and Qiita API in Python
(Bottom) Cooperation between Jupyter Notebook and running Excel
Python and numpy tips
[Python] pip and wheel
Python module (Python learning memo ④)
Create a Python module
Batch design and python
Python iterators and generators
Python packages and modules
Vue-Cli and Python integration
File write speed comparison experiment between python 2.7.9 and pypy 2.5.0
Between parametric and nonparametric
[Ruby vs Python] Benchmark comparison between Rails and Flask
Control other programs from Python (communication between Python and exe)
Difference between Ruby and Python in terms of variables
Ruby, Python and map
__future__ module and future_builtins module