Scripts:PostUrl
Jump to navigation
Jump to search
posturl Usage of postdata(url, data):
temp = postdata('http://www.yourdomain.com/postdata.php', {'field1': 'field1data', 'field2': 'field2data'})
import string import socket import os import time import sys import re import urlparse try: unicode except NameError: def _is_unicode(x): return 0 else: def _is_unicode(x): return isinstance(x, unicode) def toBytes(url): """toBytes(u"URL") --> 'URL'.""" # Most URL schemes require ASCII. If that changes, the conversion # can be relaxed if _is_unicode(url): try: url = url.encode("ASCII") except UnicodeError: raise UnicodeError("URL " + repr(url) + " contains non-ASCII characters") return url def unquote(s): """unquote('abc%20def') -> 'abc def'.""" mychr = chr myatoi = int list = s.split('%') res = [list[0]] myappend = res.append del list[0] for item in list: if item[1:2]: try: myappend(mychr(myatoi(item[:2], 16)) + item[2:]) except ValueError: myappend('%' + item) else: myappend('%' + item) return "".join(res) def unquote_plus(s): """unquote('%7e/abc+def') -> '~/abc def'""" if '+' in s: # replace '+' with ' ' s = ' '.join(s.split('+')) return unquote(s) always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' '0123456789' '_.-') _fast_safe_test = always_safe + '/' _fast_safe = None def _fast_quote(s): global _fast_safe if _fast_safe is None: _fast_safe = {} for c in _fast_safe_test: _fast_safe[c] = c res = list(s) for i in range(len(res)): c = res[i] if not c in _fast_safe: res[i] = '%%%02X' % ord(c) return ''.join(res) def quote(s, safe = '/'): """quote('abc def') -> 'abc%20def' Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted. RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists the following reserved characters. reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," Each of these characters is reserved in some component of a URL, but not necessarily in all of them. By default, the quote function is intended for quoting the path section of a URL. Thus, it will not encode '/'. This character is reserved, but in typical usage the quote function is being called on a path where the existing slash characters are used as reserved characters. """ safe = always_safe + safe if _fast_safe_test == safe: return _fast_quote(s) res = list(s) for i in range(len(res)): c = res[i] if c not in safe: res[i] = '%%%02X' % ord(c) return ''.join(res) def quote_plus(s, safe = ''): """Quote the query fragment of a URL; replacing ' ' with '+'""" if ' ' in s: l = s.split(' ') for i in range(len(l)): l[i] = quote(l[i], safe) return '+'.join(l) else: return quote(s, safe) def urlencode(query,doseq=0): """Encode a sequence of two-element tuples or dictionary into a URL query string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the parameters in the output will match the order of parameters in the input. """ if hasattr(query,"items"): # mapping objects query = query.items() else: # it's a bother at times that strings and string-like objects are # sequences... try: # non-sequence items should not work with len() # non-empty strings will fail this if len(query) and not isinstance(query[0], tuple): raise TypeError # zero-length sequences of all types will get here and succeed, # but that's a minor nit - since the original implementation # allowed empty dicts that type of behavior probably should be # preserved for consistency except TypeError: ty,va,tb = sys.exc_info() raise TypeError, "not a valid non-string sequence or mapping object", tb l = [] if not doseq: # preserve old behavior for k, v in query: k = quote_plus(str(k)) v = quote_plus(str(v)) l.append(k + '=' + v) else: for k, v in query: k = quote_plus(str(k)) if isinstance(v, str): v = quote_plus(v) l.append(k + '=' + v) elif _is_unicode(v): # is there a reasonable way to convert to ASCII? # encode generates a string, but "replace" or "ignore" # lose information and "strict" can raise UnicodeError v = quote_plus(v.encode("ASCII","replace")) l.append(k + '=' + v) else: try: # is this a sufficient test for sequence-ness? x = len(v) except TypeError: # not a sequence v = quote_plus(str(v)) l.append(k + '=' + v) else: # loop over the sequence for elt in v: l.append(k + '=' + quote_plus(str(elt))) return '&'.join(l) def postdata(url, data): print 'in postdata function' urldata = urlparse.urlparse(url) hostname = urldata[1] path = urldata[2] print hostname, path formdata = bf2.urllib.urlencode(data) print "formdata", formdata s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((hostname, 80)) s.send("POST %s HTTP/1.0\n" % path) s.send("Host: %s\n" % hostname) s.send("Connection: close\n") s.send("Content-type: application/x-www-form-urlencoded\n") contentlength = "Content-length: %s\n\n" % len(formdata) s.send(contentlength) s.send("%s" % formdata) splitter = re.compile('\r\n') while 1: buf = s.recv(1000) if not buf: break var = splitter.split(buf) s.close() return '\r\n'.join(var)