makaleler / Python Programlama / Python Web Servis Sunucu

Python Web Servis Sunucu

18.08.2017 16:56:23

Python programlama dili kullanarak Web Servis sunucu hizmeti veren yazılım örneği

Bu çalışmamız web servis sunucu hizmeti yapan bir script yazılmasını ve bu hizmetin verilerine erişebilen bir istemci tarafının kodlamasını örnekleyeceğiz.


Gerekli Paketler
apt-get install python-pip
pip install pysimplesoap

Python Web Servis Sunucu Örneği


#!/usr/bin/python
# -*- coding: utf8 -*-

from pysimplesoap.server import SoapDispatcher, SOAPHandler
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
# from http.server import HTTPServer    
                                        
def CreateOrder(a):                     
    "Return a list"                     
    return '<a>Merhaba Dunya</a> ' + a; 
                                        
dispatcher = SoapDispatcher(            
    'Entegre',                          
    location = "[url]http://localhost:8008/[/url]",
    action = '[url]http://localhost:8008/[/url]', # SOAPAction
    namespace = "[url]http://pythontr.com/get.wsdl[/url]", prefix="ns0",
    trace = True,                       
    ns = True)                          

dispatcher.register_function('CreateOrder', CreateOrder,
    returns={'list':str}, args = {'a':str})

print ("Starting server...")
httpd = HTTPServer(("", 8008), SOAPHandler)
httpd.dispatcher = dispatcher
httpd.serve_forever()


Python Web Servis İstemci Örneği


from suds.client import Client

client = Client ("[url]http://127.0.0.1:8008/[/url]")
result = client.service.CreateOrder ('a')
print result

Aşağıdaki verilen örnekler dizi olarak ve daha genişletilmiş bir yapılandırmadır.


Python Web Servis Sunucu Örneği 2


#!/usr/bin/python
# -*- coding: utf8 -*-

################################################################################
# 21.08.2017
# husonet
# Huseyin OZDEMIR
# Bu betik aktarım hizmeti vermesi icin hazirlanmistir.
################################################################################

import os
import hashlib
import cx_Oracle

from pysimplesoap.server import SoapDispatcher, SOAPHandler
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from SocketServer import ThreadingMixIn

ORACLE_DB_SUNUCU    = 'PYTHON/xxxxxx@127.0.0.1/XE'

VERSIYON = 1 

os.putenv('ORACLE_HOME','/u01/app/oracle/product/11.2.0/xe')
os.putenv('ORACLE_SID','XE')
os.putenv('NLS_LANG','.AL32UTF8')
os.putenv('PATH','$ORACLE_HOME/bin:$PATH')

# DEBUG ise 1
DEBUG = 0 

CREATE_ORDER_TEMPLATE = """ 
    <text>#aciklama#</text>
    <success>#success#</success>
    <resultDetail>
      <ResultDetail>
        <CustomerId>#customer_id#</CustomerId>
        <CevaId>#ceva_id#</CevaId>
      </ResultDetail>
    </resultDetail>
"""
#-------------------------------------------------------------------------------
# CheckUser
def CheckUser(cnn, sUserName, sPassword, sCustomerId):
    try:
        vPassword = hashlib.md5(sPassword).hexdigest()
        result = False
        cur = cnn.cursor()
        sql = '''
            SELECT ID
            from USER
            WHERE ID = :ID AND
                USERNAME = :USERNAME AND
                SIFRE = :SIFRE
        '''
        cur.execute(sql, {'ID':sCustomerId,
            'USERNAME':sUserName, 'SIFRE':vPassword})
        row = cur.fetchone()
        if row:
            result = True
    except Exception, err:
        if DEBUG:
            raise
        else:
            print(str(err))
        result = False
    return result

#-------------------------------------------------------------------------------
# CreateOrder
def CreateOrder(login, order):
    "CreateOrder Order Create"
    try:
        result = CREATE_ORDER_TEMPLATE.replace('#customer_id#', str(login['customer_id']))
        cnn = cx_Oracle.connect(ORACLE_DB_SUNUCU)
        if CheckUser(cnn, login['username'], login['password'], login['customer_id']) == False:
            result = result.replace('#aciklama#','Error User')
            result = result.replace('#success#', 'False')
            result = result.replace('#ceva_id#', '')

        cur = cnn.cursor()
        last_id = cur.var(cx_Oracle.NUMBER)
        sql = """
        INSERT INTO TMP_TEST(
            ID,
            SIRA,
            TROR_TRANSPORTATION_ORDER_TYP,
            TROR_TRANSPORTATION_PAYEE_ID,
            TRSE_CODE,
            TRSE_PAAD_CODE,
            TROR_TRANSPORTATION_CONTRACT,
            TROR_DEPOSITOR_ID,
            TROR_INVENTORY_SITE_ID,
            CUST_DESCRIPTION,
            TROR_TO_ADRESS,
            TROR_TO_CITY_ID,
            TROR_ROUTE_ID,
            CUST_PACR_REFERENCE,
            TROR_CUSTOMER_ORDER_NUMBER,
            TROR_DEPOSITOR_DOCUMENT,
            TROR_ORDER_DATE,
            TROR_PLANNED_SHIPMENT_DATE_TI,
            TROR_PLANNED_DELIVERY_DATE_TI,
            TROR_DELIVERY_NOTE,
            TROR_OFFICIAL_DOCUMENT_NO,
            TROD_CODE,
            TROD_TRANSPORT_PRODUCT_ID,
            TRPR_DESCRIPTION,
            TROD_TRANSPORT_PRODUCT_GROUP,
            TRPG_DESCRIPTION,
            TROD_CU_QUANTITY,
            TROD_CU_VRKME,
            TROD_VOLUME,
            TROD_WEIGHT,
            TROD_QUANTITY,
            TROR_NOTES,
            DUMMY1,
            DUMMY2,
            DUMMY3,
            TROR_TO_DISTRICT,
            TROR_TO_ILCE
        )
        VALUES (
            SQ_TMP_ORDER.NEXTVAL,
            :SIRA,
            :TROR_TRANSPORTATION_ORDER_TYP,
            :TROR_TRANSPORTATION_PAYEE_ID,
            :TRSE_CODE,
            :TRSE_PAAD_CODE,
            :TROR_TRANSPORTATION_CONTRACT,
            :TROR_DEPOSITOR_ID,
            :TROR_INVENTORY_SITE_ID,
            :CUST_DESCRIPTION,
            :TROR_TO_ADRESS,
            :TROR_TO_CITY_ID,
            :TROR_ROUTE_ID,
            :CUST_PACR_REFERENCE,
            :TROR_CUSTOMER_ORDER_NUMBER,
            :TROR_DEPOSITOR_DOCUMENT,
            :TROR_ORDER_DATE,
            :TROR_PLANNED_SHIPMENT_DATE_TI,
            :TROR_PLANNED_DELIVERY_DATE_TI,
            :TROR_DELIVERY_NOTE,
            :TROR_OFFICIAL_DOCUMENT_NO,
            :TROD_CODE,
            :TROD_TRANSPORT_PRODUCT_ID,
            :TRPR_DESCRIPTION,
            :TROD_TRANSPORT_PRODUCT_GROUP,
            :TRPG_DESCRIPTION,
            :TROD_CU_QUANTITY,
            :TROD_CU_VRKME,
            :TROD_VOLUME,
            :TROD_WEIGHT,
            :TROD_QUANTITY,
            :TROR_NOTES,
            :DUMMY1,
            :DUMMY2,
            :DUMMY3,
            :TROR_TO_DISTRICT,
            :TROR_TO_ILCE )
            returning ID
            into :x
        """
        sql = sql.decode("UTF-8")
        cur.prepare(sql)
        cur.execute(None, {
            'SIRA':                             order['sira'],
            'TROR_TRANSPORTATION_ORDER_TYP':    order['tror_transportation_order_typ'][:20],
            'TROR_TRANSPORTATION_PAYEE_ID' :    order['tror_transportation_payee_id'],
            'TRSE_CODE':                        order['trse_code'],
            'TRSE_PAAD_CODE':                   order['trse_paad_code'][:4],
            'TROR_TRANSPORTATION_CONTRACT':     order['tror_transportation_contract'][:3],
            'TROR_DEPOSITOR_ID':                order['tror_depositor_id'],
            'TROR_INVENTORY_SITE_ID':           order['tror_inventory_site_id'][:4],
            'CUST_DESCRIPTION':                 order['cust_description'],
            'TROR_TO_ADRESS':                   order['tror_to_adress'],
            'TROR_TO_CITY_ID':                  order['tror_to_city_id'][:3],
            'TROR_ROUTE_ID':                    order['tror_route_id'][:6],
            'CUST_PACR_REFERENCE':              order['cust_pacr_reference'][:10],
            'TROR_CUSTOMER_ORDER_NUMBER':       order['tror_customer_order_number'][:10],
            'TROR_DEPOSITOR_DOCUMENT':          order['tror_depositor_document'][:10],
            'TROR_ORDER_DATE':                  order['tror_order_date'][:10],
            'TROR_PLANNED_SHIPMENT_DATE_TI':    order['tror_planned_shipment_date_ti'][:10],
            'TROR_PLANNED_DELIVERY_DATE_TI':    order['tror_planned_delivery_date_ti'][:10],
            'TROR_DELIVERY_NOTE':               order['tror_delivery_note'][:10],
            'TROR_OFFICIAL_DOCUMENT_NO':        order['tror_official_document_no'][:16],
            'TROD_CODE':                        order['trod_code'],
            'TROD_TRANSPORT_PRODUCT_ID':        order['trod_transport_product_id'][:18],
            'TRPR_DESCRIPTION':                 order['trpr_description'],
            'TROD_TRANSPORT_PRODUCT_GROUP':     order['trod_transport_product_group'][:10],
            'TRPG_DESCRIPTION':                 order['trpg_description'][:10],
            'TROD_CU_QUANTITY':                 order['trod_cu_quantity'],
            'TROD_CU_VRKME':                    order['trod_cu_vrkme'][:3],
            'TROD_VOLUME':                      order['trod_volume'],
            'TROD_WEIGHT':                      order['trod_weight'],
            'TROD_QUANTITY':                    order['trod_quantity'],
            'TROR_NOTES':                       order['tror_notes'],
            'DUMMY1':                           order['dummy1'],
            'DUMMY2':                           order['dummy2'],
            'DUMMY3':                           order['dummy3'],
            'TROR_TO_DISTRICT':                 order['tror_to_district'][:3],
            'TROR_TO_ILCE':                     order['tror_to_ilce'],
            'x':                                last_id
        })
        cnn.commit()
        result = result.replace('#aciklama#', 'Create Order Complete')
        result = result.replace('#success#', 'True')
        result = result.replace('#ceva_id#', str(int(last_id.getvalue())))
    except Exception, err:
        if DEBUG:
            raise
        else:
            print(str(err))
        result = result.replace('#aciklama#',err)
        result = result.replace('#success#', 'False')
        result = result.replace('#ceva_id#', '')
    return result

dispatcher = SoapDispatcher(
    'Entegre',
    #location = "[url]http://localhost:8008/[/url]",
    #action = '[url]http://localhost:8008/[/url]', # SOAPAction
    location = "[url]http://xx.xxx.81.240:8008/[/url]",
    action = '[url]http://xx.xxx.81.240:8008/[/url]', # SOAPAction
    namespace = "[url]http://www.pythontr.com/get.wsdl[/url]", prefix="ns0",
    trace = True,
    ns = True)

dispatcher.register_function('CreateOrder', CreateOrder,
        returns={'xml':str},
        args = {
            'login': {
                'customer_id':int,
                'username':str,
                'password':str
            },
            'order': {
                'sira':int,
                'tror_delivery_note':str,
                'cust_pacr_reference':str,
                'tror_transportation_order_typ':str,
                'tror_transportation_payee_id':int,
                'trse_code':str,
                'trse_paad_code':str,
                'tror_transportation_contract':str,
                'tror_depositor_id':str,
                'tror_inventory_site_id':str,·
                'cust_description':str,
                'tror_to_adress':str,
                'tror_to_city_id':str,
                'tror_route_id':str,
                'tror_customer_order_number':str,
                'tror_depositor_document':str,
                'tror_order_date':str,
                'tror_planned_shipment_date_ti':str,
                'tror_planned_delivery_date_ti':str,
                'tror_official_document_no':str,
                'trod_code':int,
                'trod_transport_product_id':str,
                'trpr_description':str,
                'trod_transport_product_group':str,
                'trpg_description':str,
                'trod_cu_quantity':float,
                'trod_cu_vrkme':str,
                'trod_volume':float,
                'trod_weight':float,
                'trod_quantity':float,
                'tror_notes':str,
                'dummy1':str,
                'dummy2':str,
                'dummy3':str,
                'tror_to_district':str,
                'tror_to_ilce':str
            }
        }
    )

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

if __name__=="__main__":
    #print ("Starting server...")
    #httpd = HTTPServer(("", 8008), SOAPHandler)
    #httpd.dispatcher = dispatcher
    #httpd.serve_forever()
    server = ThreadedHTTPServer(('', 8008), SOAPHandler)
    print 'Starting server, use <Ctrl-C> to stop'
    server.dispatcher = dispatcher
    server.serve_forever()


Python Web Servis İstemci Örneği 2


from suds.client import Client
from suds.cache import NoCache

USERNAME = 'demo'
PASS = 'demo'
CUSTOMER_ID = 18

client = Client ("[url]http://xx.xxx.81.240:8008/[/url]", cache=NoCache())

Login  = {'login':{'customer_id': CUSTOMER_ID, 'username': USERNAME, 'password': PASS}}

Login = client.factory.create('CreateOrderlogin')


Login.username      = USERNAME
Login.customer_id   = CUSTOMER_ID
Login.password      = PASS

Order = client.factory.create('CreateOrderorder')

Order.sira                           =1
Order.tror_delivery_note             ='tror_delivery_note'
Order.cust_pacr_reference            ='cust_pacr_reference'
Order.tror_transportation_order_typ ='tror_transportation_order_typ'
Order.tror_transportation_payee_id   =2
Order.trse_code                      ='trse_code'
Order.trse_paad_code                 ='trse_paad_code'
Order.tror_transportation_contract   ='tror_transportation_contract'
Order.tror_depositor_id              ='tror_depositor_id'
Order.tror_inventory_site_id         ='tror_inventory_site_id'
Order.cust_description               ='cust_description'
Order.tror_to_adress                 ='tror_to_adress'
Order.tror_to_city_id                ='tror_to_city_id'
Order.tror_route_id                  ='tror_route_id'
Order.tror_customer_order_number     ='tror_customer_order_number'
Order.tror_depositor_document        ='tror_depositor_document'
Order.tror_order_date                ='tror_order_date'
Order.tror_planned_shipment_date_ti  ='tror_planned_shipment_date_ti'
Order.tror_planned_delivery_date_ti  ='tror_planned_delivery_date_ti'
Order.tror_official_document_no      ='tror_official_document_no'
Order.trod_code                      =90
Order.trod_transport_product_id      ='trod_transport_product_id'
Order.trpr_description               ='trpr_description'
Order.trod_transport_product_group   ='trod_transport_product_group'
Order.trpg_description               ='trpg_description'
Order.trod_cu_quantity               =1.0
Order.trod_cu_vrkme                  ='trod_cu_vrkme'
Order.trod_volume                    =3.0
Order.trod_weight                    =4.0
Order.trod_quantity                  =5.0
Order.tror_notes                     ='tror_notes'
Order.dummy1                         ='dummy1'
Order.dummy2                         ='dummy2'
Order.dummy3                         ='dummy3'
Order.tror_to_district               ='tror_to_district'
Order.tror_to_ilce                   ='tror_to_ilce'

co = client.factory.create('CreateOrder')
co.login = Login

co.order = Order

result = client.service.CreateOrder( login = co.login, order = co.order  )

print result
yazar husonet

Yorumlar

Bu içerik için sizde yorum yapabilirsiniz!
anasayfa | makaleler | haberler | dosyalar | linkler | hakkımızda