[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

from python script to webservice

Posted on 2011-09-14
6
Medium Priority
?
688 Views
Last Modified: 2012-05-12
I'd like to create a very simple web service that exposes the functionality from my existing python script (attached here at the end) for use within my company...  Please provide a solution and code, not links to other info.

Basically the simplest version could be this one:
INPUT:  http://www.urladdress.com/mypythonwebservice/cc?region=global"e=goog
OUTPUT: price (523.07 for google stock last time I checked).

The script I want to provide as a service is:

# modules used in this function
import re
import sys
import os
import subprocess
import ystockquote

#download the file first
os.popen("curl -L http://www.bolsadesantiago.com/Theme/preciosacciones.aspx > precioacciones.aspx")
ticker = sys.argv[1]
ticker = str(ticker)
region = sys.argv[2]
region = str(region)

# This function takes as an input the name of a stock and region being traded,
#  and goes to the acciones.aspx OR yahoo finance to find the price...
def ticker2price(ticker, region):
  if region == "chile":
    file = open("precioacciones.aspx")
    stockstxt = file.read()
    pattern = "NEMO="+ticker+".*right\">"
    result = re.search(pattern, stockstxt)
    price = stockstxt[result.end():result.end()+30]
    price = price.split('<')[0]
    price.replace( '.', '' ).replace( ',', '.' )
    price = float( price.replace( '.', '' ).replace( ',', '.' ) )
    return price

  if region == "global":
    return ystockquote.get_price(ticker)


price = ticker2price(ticker, region)
print price

NOW INSTEAD OF PRINT WANT THIS CODE TO BE A WEBSERVICE AS SPECIFIED ABOVE.

Please help me and provide code and final answer, not links to other resources.

Thanks!
0
Comment
Question by:dfernan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 

Author Comment

by:dfernan
ID: 36547313
Please help me with this Q, pleaaaaase ;-)
0
 
LVL 3

Accepted Solution

by:
defc0n1 earned 2000 total points
ID: 36592182
The easiest way to do this I can think of is to make your python script executable on your server/machine.

I assume that your are running Windows if so you can try the following:

Install python 2.5.2 as standalone - this should be no problem.

Go to the folder C:\xampp\cgi-bin\ and create a file pycgi.cgi. Paste the following code into the file and save:



      
#!C:/Python25/python.exe
# -*- coding: iso-8859-15 -*-
print "Content-Type: text/plain;charset=iso-8859-15"
print



# modules used in this function
import re
import sys
import os
import subprocess
import ystockquote

import cgi

#download the file first
os.popen("curl -L http://www.bolsadesantiago.com/Theme/preciosacciones.aspx > precioacciones.aspx")
ticker = sys.argv[1]
ticker = str(ticker)
region = sys.argv[2]
region = str(region)

region = cgi.FieldStorage()
stock = cgi.FieldStorage()


# This function takes as an input the name of a stock and region being traded,
#  and goes to the acciones.aspx OR yahoo finance to find the price...
def ticker2price(ticker, region):
  if region == "chile":
    file = open("precioacciones.aspx")
    stockstxt = file.read()
    pattern = "NEMO="+ticker+".*right\">"
    result = re.search(pattern, stockstxt)
    price = stockstxt[result.end():result.end()+30]
    price = price.split('<')[0]
    price.replace( '.', '' ).replace( ',', '.' )
    price = float( price.replace( '.', '' ).replace( ',', '.' ) )
    return price

  if region == "global":
    return ystockquote.get_price(ticker)


price = ticker2price(ticker, region)
print price

Open in new window



If this works you can start to configure apache so that it can open python files in any folder:

Create a folder "folder" in C:\xampp\htdocs\folder

Copy your pycgi.cgi to that new folder an rename it pycgi.py

Now open the apache config file C:\xampp\apache\conf\httpd.conf

Look for


      
<IfModule mime_module>
  ...
  AddHandler cgi-script .cgi
  ...
</IfModule>

Open in new window



and add
 AddHandler cgi-script .py

Open in new window


Now please restart XAMPP  - after that you should be able to call your script via http://localhost/folder/pycgi.py
0
 

Assisted Solution

by:dfernan
dfernan earned 0 total points
ID: 36592561
wow great solution, thank you very much!  however, I am using a linux server, not a windows one, do you know what I need to change to make it work on a linux server?
0
 

Author Closing Comment

by:dfernan
ID: 37360265
assumed i ma using a windows server while i explicitly mentioned I was using a unix server.
0
 
LVL 3

Expert Comment

by:defc0n1
ID: 37739737
I am sorry I missed the followup comment. On a unix or linux  server you can do this like this:


Use your according package manager and install mod_python by typing the following into your shell:

#On debian/
sudo apt-get install libapache2-mod-python

#on fedora/centOS
sudo yum install mod_python

Open in new window


Debian/Ubuntu

Open /etc/apache2/sites-available/default (make sure to make backup of configuration file) and add:

#add either this if you want to use the Publisher Handler e.g. run python scripts directly
 <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
                AddHandler mod_python .py
                PythonHandler mod_python.publisher
                PythonDebug On
        </Directory>
#or this if you want to use the PSP Handler e.g. run python inside html
 <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
                AddHandler mod_python .psp
                PythonHandler mod_python.psp
                PythonDebug On
        </Directory>

Open in new window


After that restart apache by typing:

# if you are using standard apache installation
/etc/init.d/httpd restart
#if you are using lampp/xampp
/opt/lampp/lampp stop
/opt/lampp/lampp start

Open in new window






Fedora/CentOS
Open /etc/httpd/conf.d/python.conf (make sure to make backup of configuration file) add:

#add either this if you want to use the Publisher Handler e.g. run python scripts directly
LoadModule python_module modules/mod_python.so

<Directory /var/www/html/>
  Options Indexes FollowSymLinks MultiViews
  AllowOverride None
  Order allow,deny
  allow from all
  AddHandler mod_python .py
  PythonHandler mod_python.publisher
  PythonDebug On
</Directory>

#or this if you want to use the PSP Handler e.g. run python inside html
LoadModule python_module modules/mod_python.so

<Directory /var/www/html/>
  Options Indexes FollowSymLinks MultiViews
  AllowOverride None
  Order allow,deny
  allow from all
  AddHandler mod_python .psp
  PythonHandler mod_python.psp
  PythonDebug On
</Directory>

Open in new window


After that restart apache by typing:

# if you are using standard apache installation
/etc/init.d/httpd restart
#if you are using lampp/xampp
/opt/lampp/lampp stop
/opt/lampp/lampp start

Open in new window


If you added the the first configuration using the Publisher Handler you will be able to run files ending with *.py  directly from /var/www/html/foo.py.

If you added the second configuration using PSP you can use python directly in html code called like this /var/www/html/foo.psp
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Citrix XenApp, Internet Explorer 11 set to Enterprise Mode and using central hosted sites.xml file.
Several part series to implement Internet Explorer 11 Enterprise Mode
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

650 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question