473,386 Members | 1,830 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Redirecting based on Requested URL

I have a small issue, hopefully easy for a proficient Python programmer.

I have an upload script that is going to be used accross multiple sites. Each site will submit a file to the script and I need the script to redirect the user to the appropriate URL based on the original request.

Currently the re-direct is hardcoded.

REDIRECT_TO_HOST="http://someurl.com"

Does anyone know how I can replace the hardcoded URL with the Requested URL?

Cheers.

PS. Sorry if it's a dumb question, I've been googling for ages and have found little help on the subject (at least not that I could understand)
Dec 6 '06 #1
5 2460
bartonc
6,596 Expert 4TB
I have a small issue, hopefully easy for a proficient Python programmer.

I have an upload script that is going to be used accross multiple sites. Each site will submit a file to the script and I need the script to redirect the user to the appropriate URL based on the original request.

Currently the re-direct is hardcoded.

REDIRECT_TO_HOST="http://someurl.com"

Does anyone know how I can replace the hardcoded URL with the Requested URL?

Cheers.

PS. Sorry if it's a dumb question, I've been googling for ages and have found little help on the subject (at least not that I could understand)
post a code snippet or two to give us a better idea of what's going on in your script. Please refer to "Posting Guidelines" for use of CODE TAGS. Thanks,
Barton
Dec 6 '06 #2
Ok. Here goes. This is the entire script.


Expand|Select|Wrap|Line Numbers
  1.  
  2. #!/usr/bin/python
  3.  
  4. ##
  5. ## UPLOADER SCRIPT VERSION 1.3
  6. ##
  7. ## June 24 05 - MS FTP Server doenst like ,'s
  8. ## July 15 05 - Strip any leading _'s -'s or \s's
  9. ## Aug 15 05 - Added redirect on error
  10.  
  11. # Dont forget to point this to th right python path, it may be python23 or python24 depending
  12.  
  13. import datetime
  14. import re
  15. import sys
  16. import os
  17. import getopt
  18. import errno
  19. import mimetypes
  20. import email
  21. import time
  22. import mimetools
  23. import multifile
  24. import StringIO
  25. import urllib2_file
  26. import urllib2
  27. import urllib
  28. import string
  29. import sys
  30. import getopt
  31. import httplib, mimetypes, sys, urllib2, re, time
  32.  
  33. # Multipart POST -code shamelessly ripped from
  34. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
  35.  
  36. def post_multipart(h, selector, fields, files):
  37.     """
  38.     Post fields and files to an http host as multipart/form-data.
  39.     fields is a sequence of (name, value) elements for regular form fields.
  40.     files is a sequence of (name, filename, value) elements for data to be uploaded as files
  41.     Return the server's response page.
  42.     """
  43.     content_type, body = encode_multipart_formdata(fields, files)
  44.     h.putrequest('POST', selector)
  45.     h.putheader('Content-Type', content_type)
  46.     h.putheader('Content-Length', str(len(body)))
  47.     h.putheader('Referer', 'Courier Upload<->Python interface')
  48.     h.putheader('Agent', 'Express Courier Python interface')
  49.     h.endheaders()
  50.     h.send(body)
  51.  
  52.     return h.getresponse();
  53.  
  54. def encode_multipart_formdata(fields, files):
  55.     """
  56.     fields is a sequence of (name, value) elements for regular form fields.
  57.     files is a sequence of (name, filename, value) elements for data to be uploaded as files
  58.     Return (content_type, body) ready for httplib.HTTP instance
  59.     """
  60.     BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
  61.     CRLF = '\r\n'
  62.     L = []
  63.     for (key, value) in fields:
  64.         L.append('--' + BOUNDARY)
  65.         L.append('Content-Disposition: form-data; name="%s"' % key)
  66.         L.append('')
  67.         L.append(value)
  68.     for (key, filename, value) in files:
  69.         L.append('--' + BOUNDARY)
  70.         L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
  71.         L.append('Content-Type: %s' % get_content_type(filename))
  72.         L.append('')
  73.         L.append(value)
  74.     L.append('--' + BOUNDARY + '--')
  75.     L.append('')
  76.     body = CRLF.join(L)
  77.     content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
  78.     return content_type, body
  79.  
  80. def get_content_type(filename):
  81.     return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
  82.  
  83.  
  84. from urllib import urlencode
  85.  
  86. import ConfigParser
  87. import string
  88.  
  89. REDIRECT_TO_HOST="http://someurl.com"
  90. DEST_UPLOADDIR=""
  91.  
  92.  
  93. def email_error(text=''):
  94.     import smtplib
  95.     import email.Message
  96.     import socket
  97.     global REDIRECT_TO_HOST
  98.  
  99.     message = email.Message.Message()
  100.     message["To"]      = "nab@xxx.com.au"
  101.     message["From"]    = "express@xxx.com.au"
  102.     message["Subject"] = REDIRECT_TO_HOST + " " + os.getenv("REQUEST_URI")
  103.  
  104.     message.set_payload(text)
  105.  
  106.     # try the internal mail server
  107.     try:
  108.         mailServer = smtplib.SMTP("192.168.1.XXX")
  109.     except socket.error, (ecode, reason):
  110.         #if not, use the external one
  111.         mailServer = smtplib.SMTP("mx.xxx.com.au")
  112.  
  113.     mailServer.sendmail(message["From"], message["To"], message.as_string())
  114.     mailServer.quit()
  115.  
  116.  
  117. def get_first_attachment(stream):
  118.  
  119.     # look for the PDF header followed by the PDF EOF marker, then a few chars later will be the mime seperator (some dashes etc)
  120.     # thing is, often a PDF will have multiple EOF markers so we need to look for the end mime seperator so we know whats going on
  121.  
  122.     p=re.compile("%PDF.*%%EOF.*?$",re.DOTALL)
  123.     m=p.search(stream)
  124.  
  125.     if m == None:
  126.         email_error("Could not find PDF attachment in upload \n\n"+stream)
  127.         return None
  128.     else:
  129.     start=m.start()
  130.  
  131.     #look for the last %%EOF
  132.     p=re.compile("%%EOF",re.DOTALL)
  133.     for m in re.finditer(p, stream):
  134.     end=m.end()+1 #plus one byte to cover any \r or \n
  135.  
  136.     payload=stream[start:end]
  137.  
  138.     return payload
  139.  
  140. # MIME encoding on the current courier app is a piece of shit, use regex instead
  141. def discover_filename(stream):
  142.  
  143.     # find the file name in the http session by looking for filename*"*"
  144.     p=re.compile("filename=\".*\"",re.I)
  145.     m=p.search(stream)
  146.     if ( m != None ):
  147.         fname= stream[m.start():m.end()]
  148.     else:
  149.         fname="untitled-document.pdf"
  150.  
  151.  
  152.     #strip antything microsoft...word etc
  153.     p=re.compile("microsoft.*(word|powerpoint|access|excel|office)",re.I);
  154.     fname=p.sub("",fname)
  155.  
  156.     #strip leading whitespace
  157.     p=re.compile("(filename|\"|=|\.pdf)",re.I);
  158.     fname=p.sub("",fname)
  159.  
  160.     #strip leading whitespace
  161.     p=re.compile('^\s+');
  162.     fname=p.sub("",fname)
  163.  
  164.     #strip trailing whitespace
  165.     p=re.compile('\s*$');
  166.     fname=p.sub("",fname)
  167.  
  168.     # replace any non alphanumerics with an underscore
  169.     p=re.compile("[\s\.#$%^&*,]")
  170.     fname=p.sub("_",fname)
  171.  
  172.     # replace anything upto the last / or \
  173.     p=re.compile(".*[\\\/]",re.I)
  174.     fname=p.sub("",fname)
  175.  
  176.     #strip any leading wierdos
  177.     p=re.compile("^[-_\s]")
  178.     while p.search(fname) != None:
  179.         fname=p.sub("",fname)
  180.  
  181.     return fname+".pdf"
  182.  
  183.  
  184.  
  185. if __name__ == '__main__':
  186.  
  187.  
  188.  
  189.     # read from stdin
  190.     stdin_stream=sys.stdin.read()
  191.     print "Content-type: text/html\n"    
  192.  
  193.     if stdin_stream != None:
  194.  
  195.     if len(stdin_stream)>1024:
  196.         thepdf=get_first_attachment(stdin_stream)
  197.         filename=discover_filename(stdin_stream)
  198.  
  199.         h = httplib.HTTPConnection(os.getenv("SERVER_NAME"), 80)
  200.         resp = post_multipart(h, "/express/upload/courier", [('op', 'Upload file'),('edit[form_id]', 'express_upload_courier')],[('edit[upload]', filename, thepdf)])
  201.  
  202.         loc = resp.read()
  203.         print loc
  204.  
  205.  
Dec 6 '06 #3
bartonc
6,596 Expert 4TB
REDIRECT_TO_HOST="http://someurl.com"

Does anyone know how I can replace the hardcoded URL with the Requested URL?
Ok, I see how your code works except where Requested URL comes from. If its in here:
Expand|Select|Wrap|Line Numbers
  1.     h.putrequest('POST', selector)
we'll need the format of selector.
Dec 6 '06 #4
For those interested, I've used this

Expand|Select|Wrap|Line Numbers
  1. REDIRECT_TO_HOST= "http://" + os.getenv("HTTP_HOST")
Thanks
Dec 7 '06 #5
bartonc
6,596 Expert 4TB
For those interested, I've used this

Expand|Select|Wrap|Line Numbers
  1. REDIRECT_TO_HOST= "http://" + os.getenv("HTTP_HOST")
Thanks
But where does the one you want come from?
Dec 7 '06 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

10
by: Kenneth Keeley | last post by:
Hi, I have been having problems with Gecko based browsers not redirecting properly. This is the line of code that does the redirecting: Response.Redirect ("Validation.asp?BookingNo=1234567") ...
1
by: Stu | last post by:
Hi All, I have an ASP.NET application to which I have implemented forms authentication to handle security. It is a relatively straight forward solution with all aspx pages residing in the root...
1
by: hecsan07 | last post by:
I am a novice programmer. I want to give my site the ability to remember users. I want to do this the easiest possible way--using cookies to store username and password--since I am not concerned...
2
by: Gary Coutts | last post by:
Hi, I am have problems redirecting from a login page. The login page is simple, with just 2 textboxes and one button. On the button click the routine below is called: I am using: Visual...
17
by: mansb2002 | last post by:
Hi, We recently moved our webserver from Win2K to Win2003. The application works fine. Only problem is that when user views a report as a PDF, IE does not show it. The following code is used to...
41
by: amygdala | last post by:
Hello all, I have posted a similar question in comp.lang.php in the past, but haven't had any response to it then. I kinda swept the problem under the rug since then. But I would really like to...
9
by: Jonathan Wood | last post by:
I've spent days trying to come up with a solution. I'd appreciate it if anyone can help. My site requires all users to log on. There are three different roles of users, and each user type will...
4
by: damiensawyer | last post by:
Hi, I'm trying to do something in global.asax that I would have thought to be quite simple. Basically, any request at all should get sent to another page. I actually got the code below from a...
1
by: barunva | last post by:
Hi All, Can you please answer my following question: I have two web servers; one is based on Linux Operating System and the second one is based on AIX OS, and both are geographically apart,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.