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)
5 2460
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
Ok. Here goes. This is the entire script. -
-
#!/usr/bin/python
-
-
##
-
## UPLOADER SCRIPT VERSION 1.3
-
##
-
## June 24 05 - MS FTP Server doenst like ,'s
-
## July 15 05 - Strip any leading _'s -'s or \s's
-
## Aug 15 05 - Added redirect on error
-
-
# Dont forget to point this to th right python path, it may be python23 or python24 depending
-
-
import datetime
-
import re
-
import sys
-
import os
-
import getopt
-
import errno
-
import mimetypes
-
import email
-
import time
-
import mimetools
-
import multifile
-
import StringIO
-
import urllib2_file
-
import urllib2
-
import urllib
-
import string
-
import sys
-
import getopt
-
import httplib, mimetypes, sys, urllib2, re, time
-
-
# Multipart POST -code shamelessly ripped from
-
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
-
-
def post_multipart(h, selector, fields, files):
-
"""
-
Post fields and files to an http host as multipart/form-data.
-
fields is a sequence of (name, value) elements for regular form fields.
-
files is a sequence of (name, filename, value) elements for data to be uploaded as files
-
Return the server's response page.
-
"""
-
content_type, body = encode_multipart_formdata(fields, files)
-
h.putrequest('POST', selector)
-
h.putheader('Content-Type', content_type)
-
h.putheader('Content-Length', str(len(body)))
-
h.putheader('Referer', 'Courier Upload<->Python interface')
-
h.putheader('Agent', 'Express Courier Python interface')
-
h.endheaders()
-
h.send(body)
-
-
return h.getresponse();
-
-
def encode_multipart_formdata(fields, files):
-
"""
-
fields is a sequence of (name, value) elements for regular form fields.
-
files is a sequence of (name, filename, value) elements for data to be uploaded as files
-
Return (content_type, body) ready for httplib.HTTP instance
-
"""
-
BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
-
CRLF = '\r\n'
-
L = []
-
for (key, value) in fields:
-
L.append('--' + BOUNDARY)
-
L.append('Content-Disposition: form-data; name="%s"' % key)
-
L.append('')
-
L.append(value)
-
for (key, filename, value) in files:
-
L.append('--' + BOUNDARY)
-
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
-
L.append('Content-Type: %s' % get_content_type(filename))
-
L.append('')
-
L.append(value)
-
L.append('--' + BOUNDARY + '--')
-
L.append('')
-
body = CRLF.join(L)
-
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
-
return content_type, body
-
-
def get_content_type(filename):
-
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
-
-
-
from urllib import urlencode
-
-
import ConfigParser
-
import string
-
-
REDIRECT_TO_HOST="http://someurl.com"
-
DEST_UPLOADDIR=""
-
-
-
def email_error(text=''):
-
import smtplib
-
import email.Message
-
import socket
-
global REDIRECT_TO_HOST
-
-
message = email.Message.Message()
-
message["To"] = "nab@xxx.com.au"
-
message["From"] = "express@xxx.com.au"
-
message["Subject"] = REDIRECT_TO_HOST + " " + os.getenv("REQUEST_URI")
-
-
message.set_payload(text)
-
-
# try the internal mail server
-
try:
-
mailServer = smtplib.SMTP("192.168.1.XXX")
-
except socket.error, (ecode, reason):
-
#if not, use the external one
-
mailServer = smtplib.SMTP("mx.xxx.com.au")
-
-
mailServer.sendmail(message["From"], message["To"], message.as_string())
-
mailServer.quit()
-
-
-
def get_first_attachment(stream):
-
-
# look for the PDF header followed by the PDF EOF marker, then a few chars later will be the mime seperator (some dashes etc)
-
# 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
-
-
p=re.compile("%PDF.*%%EOF.*?$",re.DOTALL)
-
m=p.search(stream)
-
-
if m == None:
-
email_error("Could not find PDF attachment in upload \n\n"+stream)
-
return None
-
else:
-
start=m.start()
-
-
#look for the last %%EOF
-
p=re.compile("%%EOF",re.DOTALL)
-
for m in re.finditer(p, stream):
-
end=m.end()+1 #plus one byte to cover any \r or \n
-
-
payload=stream[start:end]
-
-
return payload
-
-
# MIME encoding on the current courier app is a piece of shit, use regex instead
-
def discover_filename(stream):
-
-
# find the file name in the http session by looking for filename*"*"
-
p=re.compile("filename=\".*\"",re.I)
-
m=p.search(stream)
-
if ( m != None ):
-
fname= stream[m.start():m.end()]
-
else:
-
fname="untitled-document.pdf"
-
-
-
#strip antything microsoft...word etc
-
p=re.compile("microsoft.*(word|powerpoint|access|excel|office)",re.I);
-
fname=p.sub("",fname)
-
-
#strip leading whitespace
-
p=re.compile("(filename|\"|=|\.pdf)",re.I);
-
fname=p.sub("",fname)
-
-
#strip leading whitespace
-
p=re.compile('^\s+');
-
fname=p.sub("",fname)
-
-
#strip trailing whitespace
-
p=re.compile('\s*$');
-
fname=p.sub("",fname)
-
-
# replace any non alphanumerics with an underscore
-
p=re.compile("[\s\.#$%^&*,]")
-
fname=p.sub("_",fname)
-
-
# replace anything upto the last / or \
-
p=re.compile(".*[\\\/]",re.I)
-
fname=p.sub("",fname)
-
-
#strip any leading wierdos
-
p=re.compile("^[-_\s]")
-
while p.search(fname) != None:
-
fname=p.sub("",fname)
-
-
return fname+".pdf"
-
-
-
-
if __name__ == '__main__':
-
-
-
-
# read from stdin
-
stdin_stream=sys.stdin.read()
-
print "Content-type: text/html\n"
-
-
if stdin_stream != None:
-
-
if len(stdin_stream)>1024:
-
thepdf=get_first_attachment(stdin_stream)
-
filename=discover_filename(stdin_stream)
-
-
h = httplib.HTTPConnection(os.getenv("SERVER_NAME"), 80)
-
resp = post_multipart(h, "/express/upload/courier", [('op', 'Upload file'),('edit[form_id]', 'express_upload_courier')],[('edit[upload]', filename, thepdf)])
-
-
loc = resp.read()
-
print loc
-
-
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: -
h.putrequest('POST', selector)
we'll need the format of selector.
For those interested, I've used this - REDIRECT_TO_HOST= "http://" + os.getenv("HTTP_HOST")
Thanks
For those interested, I've used this - REDIRECT_TO_HOST= "http://" + os.getenv("HTTP_HOST")
Thanks
But where does the one you want come from?
Sign in to post your reply or Sign up for a free account.
Similar topics
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")
...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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,...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
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$) {
}
...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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,...
|
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...
| |