Calling python from Actionscript - python

I have an Adobe Air Program that calls a python script. I dont' think the actionscript 3.0 is making the proper call. Code:
var file:File;
var args:Vector.<String> = new Vector.<String>;
file = new File().resolvePath("/usr/bin/python");
var pyScript:File;
pyScript = File.applicationDirectory.resolvePath("python/mac/merge.py");
var tempOutPath:String = File.applicationStorageDirectory.resolvePath("out.pdf").nativePath;
args.push(pyScript.nativePath, "-w", "-o", tempOutPath, "-i");
for(var x:int; x < numFilesToProcess; x++){
var pdfPath:String = File(pdfs.getItemAt(x)).nativePath;
args.push(pdfPath);
}
callNative(file, args);
In terminal (Mac), the following works fine:
python merge.py -w -o out.pdf -i file1.pdf file2.pdf
The args.push(pyScript.native.... line is the problematic one. I'd appreciate some assistance.

I have faced a similar problem using Air. I needed to print to a receipt printer from an Air app. I couldn't do it from the app itself so I used a python RPC server to do the work for me and talked to it over http. below is a simplified version to give you an idea:
The python RPC server
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/','/RPC2')
server = SimpleXMLRPCServer(('localhost', 8123), requestHandler=RequestHandler)
def myService( arg0, arg1 ):
#do the stuff
return 0
server.register_function(myService)
server.serve_forever()
In Air I create the call as an XML string and make my request.
I haven't shown all the details as I was using javascript not actionscript so please treat this as pseudocode.
// XML as a string
// possibly create the XML and toXMLString() it?
var data:String = '
<?xml version="1.0"?>
<methodCall>
<methodName>myService</methodName>
<params>
<param>
<string>file1.pdf</string>
</param>
<param>
<string>file2.pdf</string>
</param>
</params>
</methodCall>';
var req:URLRequest = new URLRequest('localhost:8123');
rec.method = 'POST';
rec.data = data;
var loader:URLLoader = new URLLoader( req );
//etc

Related

PHP won't execute a python file

I've been getting this problem for a little while now.
The thing is that i have an HTML form proceed by PHP which looks like that:
<?php
if (isset($_POST)) {
$link = mysqli_connect("localhost", "root", "password", "tablename");
$url = $_POST['url'];
$shorturl = str_replace(['/', 'https:', 'http:'], '', $url);
$iconpath = shell_exec("python3 /home/favicon.py {$url}");
$sql = "INSERT INTO links (url, shorturl, iconpath) values ('{$url}', '{$shorturl}', '{$iconpath}')";
$result = mysqli_query($link, $sql);
}
/*
header('Location: /');
exit;
*/
?>
This code is supposed to extract the given URL from the form, execute python file that downloads favicon of the site and insert the data into a MySQL table.Python code:
import sys
import requests
url = sys.argv[1]
img_data = requests.get(f'{url}/favicon.ico').content
iconpath = '/home/favicon.png'
with open(iconpath, 'wb') as handler:
handler.write(img_data)
print(iconpath)
It all works fine except for the favicon part. When i run the python file from shell, it works fine. When i run it from PHP interactive console by the exact same code written in the form handler, it works fine. But it just won't run properly in the handler, because even when i try to debug it like
echo $iconpath;
it doesn't actually show anything in there. What can i do with it?
P.S. the code actually inserts $url and $shorturl variables into the database, so i said it all works fine except the shell_exec part

Python to Java script SendMailRequest with SourceArn and FromArn

I have here a part of a code in Python which is for AWS SendEmailRequest(SES)
response = boto3.client('ses').send_raw_email(
FromArn='response = boto3.client('ses').send_raw_email(
FromArn='arn:aws:ses:us-east-1:123456789012:identity/example.com',
SourceArn='arn:aws:ses:us-east-1:123456789012:identity/example.com',
RawMessage={
'Data': msg
},
)
This is working as expected. My problem is that I also need to have this in my Java script but I'm confused how to incorporate it. I've been trying but it seems to be not working. This is the existing Java script part below:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
message.writeTo(outputStream);
RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage)
client.sendRawEmail(rawEmailRequest);
I think the FromArn and SourceArn should be incorporated in the rawMessage or rawEmailRequest but I couldn't make it work. On the top of the code, there are values declared like this:
public class SESEMail {
static final String FROM = "example#web.com";
static final String key = Config.key;
static final String privatekey = Config.privateKey;
static Logger logger = Logger.getLogger(SESEMail.class);
public static Variables variables;
I've been reading this one but still confused with how Java language works. http://javadox.com/com.amazonaws/aws-java-sdk-ses/1.10.29/com/amazonaws/services/simpleemail/model/SendRawEmailRequest.html#getSourceArn()

Running a python script in C# after publishing C# project [duplicate]

I have been working on a problem for a while now which I cannot seem to resolve so I need some help! The problem is that I am writing a program in C# but I require a function from a Python file I created. This in itself is no problem:
...Usual Stuff
using IronPython.Hosting;
using IronPython.Runtime;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
namespace Program
{
public partial class Form1 : Form
{
Microsoft.Scripting.Hosting.ScriptEngine py;
Microsoft.Scripting.Hosting.ScriptScope s;
public Form1()
{
InitializeComponent();
py = Python.CreateEngine(); // allow us to run ironpython programs
s = py.CreateScope(); // you need this to get the variables
}
private void doPython()
{
//Step 1:
//Creating a new script runtime
var ironPythonRuntime = Python.CreateRuntime();
//Step 2:
//Load the Iron Python file/script into the memory
//Should be resolve at runtime
dynamic loadIPython = ironPythonRuntime.;
//Step 3:
//Invoke the method and print the result
double n = loadIPython.add(100, 200);
numericUpDown1.Value = (decimal)n;
}
}
}
However, this requires for the file 'first.py' to be wherever the program is once compiled. So if I wanted to share my program I would have to send both the executable and the python files which is very inconvenient. One way I thought to resolve this is by adding the 'first.py' file to the resources and running from there... but I don't know how to do this or even if it is possible.
Naturally the above code will not work for this as .UseFile method takes string arguments not byte[]. Does anyone know how I may progress?
Lets start with the simplest thing that could possibly work, you've got some code that looks a little like the following:
// ...
py = Python.CreateEngine(); // allow us to run ironpython programs
s = py.CreateScope(); // you need this to get the variables
var ironPythonRuntime = Python.CreateRuntime();
var x = py.CreateScriptSourceFromFile("SomeCode.py");
x.Execute(s);
var myFoo = s.GetVariable("myFoo");
var n = (double)myFoo.add(100, 200);
// ...
and we'd like to replace the line var x = py.CreateScriptSourceFromFile(... with something else; If we could get the embedded resource as a string, we could use ScriptingEngine.CreateScriptSourceFromString().
Cribbing this fine answer, we can get something that looks a bit like this:
string pySrc;
var resourceName = "ConsoleApplication1.SomeCode.py";
using (var stream = System.Reflection.Assembly.GetExecutingAssembly()
.GetManifestResourceStream(resourceName))
using (var reader = new System.IO.StreamReader(stream))
{
pySrc = reader.ReadToEnd();
}
var x = py.CreateScriptSourceFromString(pySrc);

Python SUDS Error

I'm trying to convert a PHP script over to python but cannot for the life of me figure out why the following is not working.
Results returned from the SOAP service query:
Suds ( https://fedorahosted.org/suds/ ) version: 0.4 GA build: R699-20100913
Service ( ExternalQueryNameAvailabilityService ) tns="http://asic.gov.au/wsdl/name/availability/external"
Prefixes (6)
ns0 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
ns1 = "http://www.w3.org/2005/05/xmlmime"
ns2 = "uri:business.document.header.types.asic.gov.au"
ns3 = "uri:external.query.name.availability.asic.gov.au"
ns4 = "uri:fss.types.asic.gov.au"
ns5 = "uri:types.asic.gov.au"
Ports (1):
(ExternalQueryNameAvailabilityPort)
Methods (1):
externalQueryNameAvailability(ns2:businessDocumentHeaderType businessDocumentHeader, ns3:requestDataType businessDocumentBody, )
Types (113):
ns0:AttributedDateTime
ns0:AttributedURI
ns0:TimestampType
ns5:abnApplicationReferenceNumberType
ns5:abnType
ns5:accountIdentifierType
ns5:actionType
ns5:addressType
ns5:addressTypeType
ns5:agentNameType
ns5:agentType
ns5:amountSignedType
ns5:amountType
ns5:applicationStatusType
ns4:ascotDocumentNoType
ns5:asicNumericIdType
ns4:asicPaymentDetailsType
ns5:asicSignatoryType
ns2:attachmentType
ns2:attachmentsType
ns1:base64Binary
ns5:birthDetailsType
ns5:bnReferenceNumberType
ns5:browserIdentifierType
ns2:businessDocumentHeaderType
ns2:businessDocumentRequestHeaderType
ns5:businessNameIdentifierType
ns5:codeType
ns5:creditCardType
ns4:customerReferenceNumberType
ns4:debtorType
ns5:descriptionType
ns5:distinguishedNameType
ns5:distinguishedWordType
ns5:documentIdentifierType
ns5:documentNoType
ns5:emailType
ns5:entityType
ns5:exceptionListType
ns5:exceptionType
ns4:feeType
ns4:feeWithAmountType
ns4:feesType
ns5:flagType
ns4:fssAccountType
ns4:fssCustomerType
ns4:fssItemType
ns4:fssSimpleAccountType
ns4:fssTransactionType
ns2:genericResultType
ns1:hexBinary
ns5:inboxIdentifierType
ns5:intervalStatusType
ns4:invoiceType
ns5:itemSearchScopeType
ns5:itemSummaryType
ns5:itemTypeType
ns5:keyType
ns4:ledgerType
ns5:lodgementIdentifierType
ns2:messageEventType
ns2:messageEventsType
ns5:messageIdentifierType
ns2:messageTimestampType
ns2:messageTimestampsType
ns5:nameAvailabilityType
ns5:nameResultType
ns5:nameResultWithObjectionsType
ns5:nameType
ns5:nniNameType
ns5:nniNumberType
ns5:objectionType
ns5:organisationIdentifierType
ns5:organisationNamePlusIdType
ns5:originatingChannelType
ns5:originatingServiceType
ns5:outboundItemIdentifierType
ns4:paymentDetailsType
ns4:paymentMethodType
ns5:paymentType
ns5:personNameBirthType
ns5:personNameType
ns5:personNameWithRoleType
ns4:priceType
ns3:queryNameAvailabilityReplyType
ns3:queryNameAvailabilityRequestType
ns5:realmIdentifierType
ns5:realmQualifierType
ns4:receiptType
ns5:referenceNoType
ns5:rejectedType
ns3:replyDataType
ns5:replyType
ns3:requestDataType
ns5:requestFailedType
ns5:requestRejectedType
ns5:requestType
ns5:resultType
ns5:signatoryType
ns5:soapSoftwareIdentifierType
ns2:softwareInformationType
ns5:standardHeaderType
ns5:standardMessageHeaderType
ns5:stateTerritoryCodeType
ns5:statusType
ns5:streetType
ns4:suffixType
ns0:tTimestampFault
ns5:telephoneNumberType
ns5:textType
ns4:transactionType
ns4:transactionsType
ns5:trueType
When trying to execute the following:
con = connect('ExternalQueryNameAvailabilityPort', test, {'Content-Type': 'application/soap+xml'})
q_header = con.factory.create('ns2:businessDocumentHeaderType')
q_header.messageType = 'queryNameAvailability'
q_header.messageVersion = '2'
q_header.messageReferenceNumber = '100'
q_header.senderType = 'REGA'
q_header.senderId = '192'
q_body = con.factory.create('ns3:businessDocumentBody')
q_body.proposedName = 'Xtramedia.net PTY LTD'
q_body.companyNameAvailabilityCheck = 'true'
q_body.bnNameAvailabilityCheck = 'true'
result = con.service.externalQueryNameAvailability(q_header, q_body)
I get the following error:
DEBUG:suds.client:http failed:
<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope">
<S:Body>
<S:Fault xmlns:ns4="http://schemas.xmlsoap.org/soap/envelope/">
<S:Code>
<S:Value>S:Receiver</S:V6alue>
</S:Code>
<S:Reason>
<S:Text xml:lang="en">org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'ns1:businessDocumentHeader'. One of '{"uri:business.document.header.types.asic.gov.au":businessDocumentHeader}' is expected
</S:Text>
</S:Reason>
</S:Fault>
</S:Body>
</S:Envelope>
Any ideas why it would be complaining about that element? - I've tried removed the "nsX" part of the element declaration but same thing.
UPDATE: The following is what the PHP Script generates and is successfull;
<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:ns1="uri:business.document.header.types.asic.gov.au" xmlns:ns2="uri:external.query.name.availability.asic.gov.au">
<env:Body>
<ns2:request>
<ns1:businessDocumentHeader>
<ns1:messageType>queryNameAvailability</ns1:messageType>
<ns1:messageReferenceNumber>1</ns1:messageReferenceNumber>
<ns1:messageVersion>2</ns1:messageVersion>
<ns1:senderId>192</ns1:senderId>
<ns1:senderType>REGA</ns1:senderType>
</ns1:businessDocumentHeader>
<ns2:businessDocumentBody>
<ns2:proposedName>TEST</ns2:proposedName>
<ns2:bnNameAvailabilityCheck>true</ns2:bnNameAvailabilityCheck>
</ns2:businessDocumentBody>
</ns2:request>
</env:Body>
</env:Envelope>
Anyone got any ideas?
UPDATE 2: I had to install the latest version of SUDS to get this working. - Thanks all for your answers much appreciated.
Cheers,
Ben
Update (after the PHP example output)
It is unclear why suds uses {uri:external.query.name.availability.asic.gov.au}
instead of {uri:business.document.header.types.asic.gov.au} for businessDocumentHeader element.
The quick and dirty way to fix it is to use suds.plugin e.g.:
from suds.plugin import MessagePlugin
class NsHeaderPlugin(MessagePlugin):
def sending(self, context):
context.envelope = context.envelope.replace('ns1:businessDocumentHeader',
'ns0:businessDocumentHeader')
Or
class NsHeaderPlugin(MessagePlugin):
def marshalled(self, context):
hdr = context.envelope.childAtPath('Body/request/businessDocumentHeader')
hdr.setPrefix('hdr', 'uri:business.document.header.types.asic.gov.au')
The 2nd argument should be ns3:requestDataType, not ns3:businessDocumentBody as you specified.
The general code flow:
from suds.client import Client # pip install suds
#XXX: change envelope namespace
from suds.bindings import binding
binding.envns = (binding.envns[0], 'http://www.w3.org/2003/05/soap-envelope')
del binding
# change content type
headers = {'Content-Type': 'application/soap+xml; charset="UTF-8"'}
client = Client(wsdl_url, headers=headers, plugins=[NsHeaderPlugin()])
header = client.factory.create('{uri:business.document.header.types.asic.gov.au}'
'businessDocumentHeaderType')
header.messageType = "queryNameAvailability"
header.messageReferenceNumber = 1
header.messageVersion = 2
header.senderId = 192
header.senderType = "REGA"
body = client.factory.create('{uri:external.query.name.availability.asic.gov.au}'
'requestDataType')
body.proposedName = 'TEST'
body.bnNameAvailabilityCheck = 'true'
# make the call
result = client.service.externalQueryNameAvailability(header, body)
print result # for debugging, to find out what attributes are available
I don't see undefined namespaces so it seems ImportDoctor is not necessary in your case. But, for example, if there were xs:string type used and 'http://schemas.xmlsoap.org/soap/encoding/' is not mentioned then you could fix the wsdl schema:
from suds.xsd.doctor import Import, ImportDoctor
imp = Import('http://schemas.xmlsoap.org/soap/encoding/')
# add namespaces where the type is used (call `imp.filter.add` multiple times)
imp.filter.add("http://asic.gov.au/wsdl/name/availability/external")
doctor = ImportDoctor(imp)
client = Client(wsdl_url, doctor=doctor)
The error pretty much tells you exactly where you need to look:
<S:Text xml:lang="en">org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'ns1:businessDocumentHeader'. One of '{"uri:business.document.header.types.asic.gov.au":businessDocumentHeader}' is expected
ns1 references the URL http://www.w3.org/2005/05/xmlmime. If visit that in your browser, you can see that there isn't much to it. That further rules out that ns1 is correct.
Since ns1:businessDocumentHeader isn't even in the list of types determined by the WSDL, you might have to make use of the ImportDoctor. I've run into similar issue in the past on a personal project of mine where the WSDL didn't correctly import the types.
I'm sorry this response isn't conclusive, but it's very difficult determine the exact fix since I can't see your WSDL. Try tinkering with the docs for the ImportDoctor and see if that doesn't help.
Try starting with this:
from suds.xsd.doctor import Import, ImportDoctor
imp = Import("http://www.w3.org/2005/05/xmlmime")
imp.filter.add("uri:business.document.header.types.asic.gov.au")
doctor = ImportDoctor(imp)
And then pass doctor=doctor to the client constructor.

how can i pass xml format data from flex to python

i want to pass xml format data into python from flex.i know how to pass from flex but my question is how can i get the passed data in python and then the data should be inserted into mysql.and aslo i want to retrieve the mysql data to the python(cgi),the python should convert all the data into xml format,and pass all the data to the flex..
Thank's in advance.....
See http://www.artima.com/weblogs/viewpost.jsp?thread=208528 for more details, here is a breif overview of what I think you are looking for.
The SimpleXMLRPCServer library allows you to easily create a server. Here's about the simplest server you can create, which provides two services to manipulate strings:
import sys
from random import shuffle
from SimpleXMLRPCServer import SimpleXMLRPCServer
class MyFuncs:
def reverse(self, str) :
x = list(str);
x.reverse();
return ''.join(x);
def scramble(self, str):
x = list(str);
shuffle(x);
return ''.join(x);
server = SimpleXMLRPCServer(("localhost", 8000))
server.register_instance(MyFuncs())
server.serve_forever()
Once you make a connection to the server, that server acts like a local object. You call the server's methods just like they're ordinary methods of that object.
This is about as clean an RPC implementation as you can hope for (and other Python RPC libraries exist; for example, CORBA clients). But it's all text based; not very satisfying when trying to create polished applications with nice GUIs. What we'd like is the best of all worlds -- Python (or your favorite language) doing the heavy lifting under the covers, and Flex creating the user experience.
To use the library, download it and unpack it somewhere. The package includes all the source code and the compiled as3-rpclib.swc library -- the .swc extension indicates an archive file, and pieces of this library can be pulled out and incorporated into your final .swf. To include the library in your project, you must tell Flexbuilder (you can get a free trial or just use the free command-line tools, and add on the Apollo portion) where the library is located by going to Project|Properties and selecting "Apollo Build Path," then choosing the "Library path" tab and pressing the "Add SWC..." button. Next, you add the namespace ak33m to your project as seen in the code below, and you're ready to create an XMLRPCObject.
Note: the only reason I used Apollo here was that I was thinking in terms of desktop applications with nice UIs. You can just as easily make it a Flex app.
Here's the entire Apollo application as a single MXML file, which I'll explain in detail:
<?xml version="1.0" encoding="utf-8"?>
<mx:ApolloApplication xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:ak33m="http://ak33m.com/mxml" layout="absolute">
<mx:Form>
<mx:FormHeading label="String Modifier"/>
<mx:FormItem label="Input String">
<mx:TextInput id="instring" change="manipulate()"/>
</mx:FormItem>
<mx:FormItem label="Reversed">
<mx:Text id="reversed"/>
</mx:FormItem>
<mx:FormItem label="Scrambled">
<mx:Text id="scrambled"/>
</mx:FormItem>
</mx:Form>
<ak33m:XMLRPCObject id="server" endpoint="http://localhost:8000"/>
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.AsyncToken;
import mx.controls.Alert;
import mx.collections.ItemResponder;
private function manipulate() : void {
server.reverse(instring.text).addResponder(new ItemResponder(reverseResult, onFault));
server.scramble(instring.text).addResponder(new ItemResponder(scrambleResult, onFault));
}
private function reverseResult(event : ResultEvent, token : AsyncToken = null) : void {
reversed.text = event.result.toString();
}
private function scrambleResult(event : ResultEvent, token : AsyncToken = null) : void {
scrambled.text = event.result.toString();
}
private function onFault (event : FaultEvent, token : AsyncToken = null) : void {
Alert.show(event.fault.faultString, event.fault.faultCode);
}
]]>
</mx:Script>
</mx:ApolloApplication>

Categories

Resources