How can I create a basic Soap server with spyne in django - django

I want to create a server which uses Django and make and take response as SOAP, so I try to use spyne for this reason but I can't run the given code
class HelloWorldService(ServiceBase):
#rpc(Unicode, Integer, _returns=Iterable(Unicode))
def say_hello(ctx, name, times):
"""Docstrings for service methods appear as documentation in the wsdl.
<b>What fun!</b>
#param name the name to say hello to
#param times the number of times to say hello
#return the completed array
"""
for i in range(times):
yield u'Hello, %s' % name
application = Application([HelloWorldService], 'spyne.examples.hello.soap',
in_protocol=Soap11(validator='lxml'),
out_protocol=Soap11())
wsgi_application = WsgiApplication(application)
if __name__ == '__main__':
import logging
from wsgiref.simple_server import make_server
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)
logging.info("listening to http://127.0.0.1:8000")
logging.info("wsdl is at: http://localhost:8000/?wsdl")
server = make_server('127.0.0.1', 8000, wsgi_application)
server.serve_forever()

Remove validator='lxml' option in in_protocol
I don't know the reason, the validator took a long time response or did not work.
And add import statements
from spyne import Application, rpc, ServiceBase, Iterable, Integer, Unicode
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication
class HelloWorldService(ServiceBase):
#rpc(Unicode, Integer, _returns=Iterable(Unicode))
def say_hello(ctx, name, times):
"""Docstrings for service methods appear as documentation in the wsdl.
<b>What fun!</b>
#param name the name to say hello to
#param times the number of times to say hello
#return the completed array
"""
for i in range(times):
yield u'Hello, %s' % name
application = Application([HelloWorldService], 'spyne.examples.hello.soap',
in_protocol=Soap11(),
out_protocol=Soap11())
wsgi_application = WsgiApplication(application)
if __name__ == '__main__':
import logging
from wsgiref.simple_server import make_server
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)
logging.info("listening to http://127.0.0.1:8000")
logging.info("wsdl is at: http://localhost:8000/?wsdl")
server = make_server('127.0.0.1', 8000, wsgi_application)
server.serve_forever()
This is my test result by Postman and curl
Body of POST commend
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<say_hello xmlns="spyne.examples.hello.soap">
<name>Tom Cruise</name>
<times>3</times>
</say_hello>
</soap:Body>
</soap:Envelope>
curl POST commend with XML lint for terminal pipeline
$ curl --location --request POST 'http://localhost:8000' --header 'Content-Type: text/xml; charset=utf-8' --header 'SOAPAction: say_hello' --data-raw '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<say_hello xmlns="spyne.examples.hello.soap">
<name>Tom Cruise</name>
<times>3</times>
</say_hello>
</soap:Body>
</soap:Envelope>
' | xmllint --format -
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 707 100 427 100 280 9319 6111 --:--:-- --:--:-- --:--:-- 15711
<?xml version="1.0" encoding="UTF-8"?>
<soap11env:Envelope xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tns="spyne.examples.hello.soap">
<soap11env:Body>
<tns:say_helloResponse>
<tns:say_helloResult>
<tns:string>Hello, Tom Cruise</tns:string>
<tns:string>Hello, Tom Cruise</tns:string>
<tns:string>Hello, Tom Cruise</tns:string>
</tns:say_helloResult>
</tns:say_helloResponse>
</soap11env:Body>
</soap11env:Envelope>
And my python version and spyne version
$ python --version
Python 3.10.4
$ pip show spyne
Name: spyne
Version: 2.14.0

Related

Requested resource '{spyne.examples.django}' not found

I am trying to develop a soap service in Django using Spyne. I've cloned spyne for app 'Hello_world' in Django application, but I get an error. Could anyone help me with it please?
My codes is similar to the one below:
app = Application([HelloWorldService], 'spyne.examples.hello.http',
in_protocol=HttpRpc(),
out_protocol=Soap11(),
)
but the following error occurs:
<faultcode>soap11env:Client.ResourceNotFound</faultcode>
<faultstring>Requested resource '{spyne.examples.django}' not found</faultstring>
<faultactor/>
There is no handler defined for the root url:
https://github.com/plq/spyne/blob/b3b3f198b6148a498cdaeda9897307e0c5b1aac1/examples/django/rpctest/urls.py#L40
After you switch the input protocol to HttpRpc and do this:
curl -D - localhost:8000/hello_world/
You get:
<?xml version='1.0' encoding='UTF-8'?>
<soap11env:Envelope xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/">
<soap11env:Body>
<soap11env:Fault>
<faultcode>soap11env:Client.ResourceNotFound</faultcode>
<faultstring>Requested resource u'{spyne.examples.django}' not found</faultstring>
<faultactor></faultactor>
</soap11env:Fault>
</soap11env:Body></soap11env:Envelope>
That's because you didn't specify which method to call.
The HelloWorldService in that example defines the say_hello function. You can call that.
curl -D - "localhost:8000/hello_world/say_hello"
Now this finds the method but you get a traceback (which I won't include here) because of non-validated input being passed to your function.
If you pass all the parameters:
curl -D - "localhost:8000/hello_world/say_hello?times=5&name=Fatemeh"
You get:
<?xml version='1.0' encoding='UTF-8'?>
<soap11env:Envelope xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tns="spyne.examples.django">
<soap11env:Body><tns:say_helloResponse>
<tns:say_helloResult>
<tns:string>Hello, Fatemeh</tns:string>
<tns:string>Hello, Fatemeh</tns:string>
<tns:string>Hello, Fatemeh</tns:string>
<tns:string>Hello, Fatemeh</tns:string>
<tns:string>Hello, Fatemeh</tns:string>
</tns:say_helloResult></tns:say_helloResponse></soap11env:Body></soap11env:Envelope>
You may want to enable validation to avoid Server exceptions. First we add Mandatory markers to input types:
from spyne import M
class HelloWorldService(Service):
#rpc(M(Unicode), M(Integer), _returns=Iterable(Unicode))
def say_hello(ctx, name, times):
for i in range(times):
yield 'Hello, %s' % name
Then we enable soft validation (the only one for HttpRpc)
app = Application([HelloWorldService], 'spyne.examples.hello.http',
in_protocol=HttpRpc(validator='soft'),
out_protocol=Soap11(),
)
After server restart and the following:
curl -D - "localhost:8000/hello_world/say_hello"
You get:
<class 'spyne.model.complex.say_hello'>.name member must occur at least 1 times.
I hope this helps!
You may need to use in_protocol Soap11 as well.
from spyne.application import Application
app = Application([HelloWorldService], 'spyne.examples.hello.http',
in_protocol=Soap11(validator='lxml'),
out_protocol=Soap11(),
)
You can check ref link.

Implementing Freshsales API in Python [duplicate]

This question already has answers here:
Python request with authentication (access_token)
(8 answers)
Closed 4 years ago.
I am trying to integrate Freshsales functionality within my Django server in order to create leads, schedule appointments, etc. Freshsale's API Documentation in Python lacks detail, however. Here is a link to their API functionality using curl commands: https://www.freshsales.io/api/.
Their python code is as follows:
from .freshsales_exception import FreshsalesException
import requests
import json
def _request(path, payload):
try:
data = json.dumps(payload)
headers = { 'content-type': 'application/json', 'accept': 'application/json' }
resp = requests.post(path, data=data, headers=headers)
if resp.status_code != 200:
raise FreshsalesException("Freshsales responded with the status code of %s" % str(resp.status_code))
except requests.exceptions.RequestException as e:
raise FreshsalesException(e.message)
In the case of the curl command, for example, to create an appointment, is:
curl -H "Authorization: Token token=sfg999666t673t7t82" -H "Content-Type: application/json" -d '{"appointment":{"title":"Sample Appointment","description":"This is just a sample Appointment.","from_date":"Mon Jun 20 2016 10:30:00 GMT+0530 (IST)","end_date":"Mon Jun 20 2016 11:30:00 GMT+0530 (IST)","time_zone":"Chennai","location":"Chennai, TN, India","targetable_id":"115765","targetable_type":"Lead", "appointment_attendees_attributes":[{ "attendee_type":"FdMultitenant::User","attendee_id":"223"},{"attendee_type":"FdMultitenant::User","attendee_id":"222"},{"attendee_type":"Lead","attendee_id":"115773"}] }}' -X POST
I understand that I need to use the requests library to make a post request. However, I do not understand how I need to format the request. The furthest extent I understand to list all appointments, for example, is for my request to be the following:
my_request = "https://mydomain.freshsales.io/api/appointments/token=myexampletoken"
response = requests.post(myrequest)
I am unsure of how to create the payload to be accepted by the API to create an appointment. How might I use the requests library to accomplish this? I have searched for how to execute curl commands in Python, and the only answers I ever saw were to use the requests library. Any help is greatly appreciated!
You're missing the Authorization header. You just need to translate curl headers -H to python code. This should work, according to your syntax.
headers = {
'content-type': 'application/json',
'accept': 'application/json'
'Authorization': 'Token token=sfg999666t673t7t82'
}

How to pass MultiValueDict which contains file objects (django request attribute) in apache bench?

I am accessing the file using request.FILES in django views.
def upload_file(request):
upload_files = request.FILES.getlist('myfile')
...
Can anyone please tell me how to pass a file (image/video/doc etc) in ab command, so that django view can read the file from MultiValueDict object?
Followed this tutorial and checked out various posts on stack overflow
Command am using is:
ab -n 10 -c 2 -p /opt/file_data.txt -T "multipart/form-data; boundary=1234567890" http://localhost/app/media
Contents of file_data.txt are
--1234567890
Content-Disposition: form-data; name="ID"
3
--1234567890
Content-Disposition: form-data; name="myfile"; filename="1.png"
Content-Type: image/png
[base64 encoded file content here]
--1234567890--
I printed logs in django server, and am getting MultiValueDict as empty object.
Thanks for your response in advance!

Error 500 when running exec start with Docker Remote API

I am using Docker Remote Api and python requests v2.2.1 to run an exec statement. This is the code I'm using:
import requests
import json
containerName = 'my_container_name'
startContainerRequest = requests.post('http://127.0.0.1:4243/containers/' + containerName + '/start')
print startContainerRequest.status_code #result: 204
payload = {'Cmd':["date"]}
headers = {'Content-type': 'application/json'}
execCreateRequest = requests.post('http://127.0.0.1:4243/containers/' + containerName + '/exec', data=json.dumps(payload), headers=headers)
print execCreateRequest.status_code #result: 201
execStartRequest = requests.post('http://127.0.0.1:4243/exec/' + execCreateRequest.json()['Id'] + '/start', headers=headers)
print execStartRequest.status_code #result: 500
print execStartRequest.text #EOF
The last REST request fails. Exec inspect works with the same id, so the id isn't the problem. Using a different command than date in the payload fails as well. I tried with different containers, but got the same results.
Running docker exec my_container_name date from the terminal works.
Here are my DOCKER_OPTS from /etc/default/docker:
DOCKER_OPTS="--dns *privateDNS* --dns 8.8.8.8 -H tcp://0.0.0.0:4243 -H unix:///var/run/docker.sock"
Add a JSON body to the Exec start POST request
POST /exec/e90e34656806/start HTTP/1.1
Content-Type: application/json
{
"Detach": false,
"Tty": false
}

Not able to create objects in Powershell for invoking a web service

This might be a silly question. Please forgive me if it is so.
My objective is to call a https web service developed in Java and Axis2 from powershell script.
Below is a sample web service which I created and I am not even able to invoke this via powershell.
Web Service Method Implementation
package com.webservice;
public class AreaOperations
{
public Area calculateArea(Dimension dimension)
{
Area area = new Area();
area.setArea(dimension.getLength() * dimension.getBreadth());
return area;
}
}
Soap Request
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:web="http://webservice.com" xmlns:xsd="http://webservice.com/xsd">
<soap:Header/>
<soap:Body>
<web:calculateArea>
<!--Optional:-->
<web:dimension>
<!--Optional:-->
<xsd:breadth>100</xsd:breadth>
<!--Optional:-->
<xsd:length>200</xsd:length>
</web:dimension>
</web:calculateArea>
</soap:Body>
</soap:Envelope>
I followed the stack exchange link In Powershell to consume a Soap complexType to keep a Soap service hot to create the following power shell script
PSScript
$URI="http://localhost:8080/axis2/services/AreaOperations?wsdl"
$proxy=New-WebServiceProxy -uri $URI
#get autogenerated namespace
$type = $proxy.GetType().Namespace
#create the data type
$CalculateAreaRequestDT = ($type + '.calculateArea')
$DimensionDT = ($type + '.dimension')
#create objects
$areaRequest = new-object ($CalculateAreaRequestDT)
$dimension = new-object ($DimensionDT)
# Assign values
$dimension.length="200"
$dimension.width="100"
$areaRequest.dimension=$dimension
#Tada
$proxy.authenticateUser($areaRequest)
However I am getting the following error when I execute the line $areaRequest = new-object ($CalculateAreaRequestDT)
New-Object : Cannot find type [Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy12_services_AreaOperations_wsdl.calculateArea]: make sure the assembly containing this type is loaded.
At line:1 char:26
+ $areaRequest = new-object <<<< ($CalculateAreaRequestDT)
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
Can you please help me resolve this issue.
Also we need to access the enterprise webservice using a P12 certificate, If some one shed the light on accessing these secured web service via powershell, it would be greatly helpful.
Note: Post edited to reflect the changes in our PROD environment as and also as per the Keith Hill's comment