本文整理汇总了Python中mechanize.Browser.add_file方法的典型用法代码示例。如果您正苦于以下问题:Python Browser.add_file方法的具体用法?Python Browser.add_file怎么用?Python Browser.add_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mechanize.Browser
的用法示例。
在下文中一共展示了Browser.add_file方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import add_file [as 别名]
class StatusServer:
default_host = "webkit-commit-queue.appspot.com"
def __init__(self, host=default_host):
self.set_host(host)
self.browser = Browser()
def set_host(self, host):
self.host = host
self.url = "http://%s" % self.host
def results_url_for_status(self, status_id):
return "%s/results/%s" % (self.url, status_id)
def _add_patch(self, patch):
if not patch:
return
if patch.bug_id():
self.browser["bug_id"] = str(patch.bug_id())
if patch.id():
self.browser["patch_id"] = str(patch.id())
def _add_results_file(self, results_file):
if not results_file:
return
self.browser.add_file(results_file, "text/plain", "results.txt", 'results_file')
def _post_to_server(self, queue_name, status, patch, results_file):
if results_file:
# We might need to re-wind the file if we've already tried to post it.
results_file.seek(0)
update_status_url = "%s/update-status" % self.url
self.browser.open(update_status_url)
self.browser.select_form(name="update_status")
self.browser['queue_name'] = queue_name
self._add_patch(patch)
self.browser['status'] = status
self._add_results_file(results_file)
return self.browser.submit().read() # This is the id of the newly created status object.
def update_status(self, queue_name, status, patch=None, results_file=None):
# During unit testing, host is None
if not self.host:
return
log(status)
return NetworkTransaction().run(lambda: self._post_to_server(queue_name, status, patch, results_file))
def patch_status(self, queue_name, patch_id):
update_status_url = "%s/patch-status/%s/%s" % (self.url, queue_name, patch_id)
try:
return urllib2.urlopen(update_status_url).read()
except urllib2.HTTPError, e:
if e.code == 404:
return None
raise e
示例2: _mapgen_speed_fired
# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import add_file [as 别名]
def _mapgen_speed_fired(self):
test_dir(join(self.dirname, 'gps_vis'))
br = Browser()
# Ignore robots.txt
br.set_handle_robots( False )
# Google demands a user-agent that isn't a robot
br.addheaders = [('User-agent', 'Firefox')]
resp1 = br.open( "http://www.gpsvisualizer.com/map_input" )
# Select the search box and search for 'foo'
br.select_form( name='main' )
br.form['width'] = '870'
br.form['height'] = '600'
br.set_value(['google_openstreetmap'], name='bg_map')
br.set_value(['speed'], name='trk_colorize')
br.form['legend_steps'] = '10'
br.add_file(open(self.filename_converted), "text/plain", self.filename_converted, name='uploaded_file_1')
# Get the search results
resp2 = br.submit()
resp = None
for link in br.links():
siteMatch = re.compile( 'download/' ).search( link.url )
if siteMatch:
resp = br.follow_link( link )
break
# Print the site
content = resp.get_data()
ofile = open(join(self.dirname, 'gps_vis', 'map_speed.html'),'w')
ofile.write(content)
ofile.close()
br.close()
print 'map generated (speed color)'
示例3: _profilegen_fired
# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import add_file [as 别名]
def _profilegen_fired(self):
test_dir(join(self.dirname, 'gps_vis'))
br = Browser()
# Ignore robots.txt
br.set_handle_robots( False )
# Google demands a user-agent that isn't a robot
br.addheaders = [('User-agent', 'Firefox')]
# Retrieve the Google home page, saving the response
resp1 = br.open( "http://www.gpsvisualizer.com/profile_input" )
# Select the search box and search for 'foo'
br.select_form( name='main' )
br.form['width'] = '870'
br.form['height'] = '250'
br.form['legend_steps'] = '10'
br.add_file(open(self.filename_converted), "text/plain", self.filename_converted, name='uploaded_file_1')
# Get the search results
resp2 = br.submit()
resp = None
for link in br.links():
siteMatch = re.compile( 'download/' ).search( link.url )
if siteMatch:
resp = br.follow_link( link )
break
# Print the site
content = resp.get_data()
ofile = open(join(self.dirname, 'gps_vis', 'profile.png'),'wb')
ofile.write(content)
ofile.close()
br.close()
print 'profile generated'
示例4: __init__
# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import add_file [as 别名]
class LEAMsite:
def __init__(self, site, user, passwd):
self.site = site
self.error = False
self.b = Browser()
self.b.set_handle_robots(False)
try:
self.b.open(site)
except urllib2.URLError:
self.error = True
return
try:
# try and log in from the portlet
self.b.select_form('loginform')
except:
# try logging in from the main login page
self.b.open('/'.join((site,"login_form")))
self.b.select_form(nr=1)
self.b['__ac_name'] = user
self.b['__ac_password'] = passwd
r = self.b.open(self.b.click())
# plone changes have rendered this inoperable
# capture the response and look in the content
# body tag has class with login failure
def checkURL(self, url):
"""Tries to open a URL and return true if successful (object exists)
or false if error occurs.
"""
try:
rsp = self.b.open(url)
except:
return False
return True
def getURL(self, url, data=None, filename=None):
"""Simple interface for retrieving the contents of a URL
and writing it to a file or returning it as stringIO.
"""
#sys.stderr.write('getURL %s\n' % url)
rsp = self.b.open(url, data)
if filename:
f = file("./Inputs/"+filename, 'wb') # always write to Input folder
f.write(rsp.read())
f.close()
return None
else:
return StringIO(rsp.read())
def putFileURL(self, filename, url,
fileobj=None, title=None, type='text/plain'):
"""Simple interface for uploading a file to a plone site.
<URL> should be an existing folder on the site and
<filename> should be a readable file.
"""
#sys.stderr.write('putFileURL %s to %s\n' % (filename,url))
if not title: title = path.basename(filename)
if not fileobj: fileobj = open(filename, 'rb')
self.b.open('/'.join((url,'createObject?type_name=File')))
self.b.select_form("edit_form")
self.b['title'] = title
self.b.add_file(fileobj, type, path.basename(filename))
# form = self.b.find_control('file_delete')
# form.value = ["",]
self.b.submit("form.button.save")
# r = self.b.open(self.b.click())
# should check that it worked
def getFile(self, url, filename=None):
""" getFile -- gets a file using standard download from Plone site
url: The URL is pointer to the file on the Plone site
filename: optional filename where data will be written
"""
rsp = self.b.open(url_join(url,'at_download/file'))
if filename:
f = open(filename, 'wb')
f.write(rsp.read())
f.close()
return None
else:
return rsp.read()
def saveFile(self, url, dir=".", at_download=False):
"""Reads the response from a URL and saves it to a local
#.........这里部分代码省略.........
示例5: __init__
# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import add_file [as 别名]
#.........这里部分代码省略.........
def fetch_patches_from_commit_queue(self):
patches_to_land = []
for bug_id in self.fetch_bug_ids_from_commit_queue():
patches = self.fetch_reviewed_patches_from_bug(bug_id)
patches_to_land += patches
return patches_to_land
def authenticate(self):
if self.authenticated:
return
if self.dryrun:
log("Skipping log in for dry run...")
self.authenticated = True
return
(username, password) = read_credentials()
log("Logging in as %s..." % username)
self.browser.open(self.bug_server_url + "index.cgi?GoAheadAndLogIn=1")
self.browser.select_form(name="login")
self.browser["Bugzilla_login"] = username
self.browser["Bugzilla_password"] = password
response = self.browser.submit()
match = re.search("<title>(.+?)</title>", response.read())
# If the resulting page has a title, and it contains the word "invalid" assume it's the login failure page.
if match and re.search("Invalid", match.group(1), re.IGNORECASE):
# FIXME: We could add the ability to try again on failure.
error("Bugzilla login failed: %s" % match.group(1))
self.authenticated = True
def add_patch_to_bug(self, bug_id, patch_file_object, description, comment_text=None, mark_for_review=False):
self.authenticate()
log('Adding patch "%s" to bug %s' % (description, bug_id))
if self.dryrun:
log(comment_text)
return
self.browser.open(self.bug_server_url + "attachment.cgi?action=enter&bugid=" + bug_id)
self.browser.select_form(name="entryform")
self.browser["description"] = description
self.browser["ispatch"] = ("1",)
if comment_text:
log(comment_text)
self.browser["comment"] = comment_text
self.browser["flag_type-1"] = ("?",) if mark_for_review else ("X",)
self.browser.add_file(patch_file_object, "text/plain", "bug-%s-%s.patch" % (bug_id, timestamp()))
self.browser.submit()
def obsolete_attachment(self, attachment_id, comment_text=None):
self.authenticate()
log("Obsoleting attachment: %s" % attachment_id)
if self.dryrun:
log(comment_text)
return
self.browser.open(self.attachment_url_for_id(attachment_id, "edit"))
self.browser.select_form(nr=1)
self.browser.find_control("isobsolete").items[0].selected = True
# Also clear any review flag (to remove it from review/commit queues)
self.browser.find_control(type="select", nr=0).value = ("X",)
if comment_text:
log(comment_text)
# Bugzilla has two textareas named 'comment', one is somehow hidden. We want the first.
self.browser.set_value(comment_text, name="comment", nr=0)
self.browser.submit()
def post_comment_to_bug(self, bug_id, comment_text):
self.authenticate()
log("Adding comment to bug %s" % bug_id)
if self.dryrun:
log(comment_text)
return
self.browser.open(self.bug_url_for_bug_id(bug_id))
self.browser.select_form(name="changeform")
self.browser["comment"] = comment_text
self.browser.submit()
def close_bug_as_fixed(self, bug_id, comment_text=None):
self.authenticate()
log("Closing bug %s as fixed" % bug_id)
if self.dryrun:
log(comment_text)
return
self.browser.open(self.bug_url_for_bug_id(bug_id))
self.browser.select_form(name="changeform")
if comment_text:
log(comment_text)
self.browser["comment"] = comment_text
self.browser["bug_status"] = ["RESOLVED"]
self.browser["resolution"] = ["FIXED"]
self.browser.submit()
示例6: __init__
# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import add_file [as 别名]
#.........这里部分代码省略.........
(username, password) = read_credentials()
log("Logging in as %s..." % username)
self.browser.open(self.bug_server_url + "index.cgi?GoAheadAndLogIn=1")
self.browser.select_form(name="login")
self.browser['Bugzilla_login'] = username
self.browser['Bugzilla_password'] = password
response = self.browser.submit()
match = re.search("<title>(.+?)</title>", response.read())
# If the resulting page has a title, and it contains the word "invalid" assume it's the login failure page.
if match and re.search("Invalid", match.group(1), re.IGNORECASE):
# FIXME: We could add the ability to try again on failure.
raise BugzillaError("Bugzilla login failed: %s" % match.group(1))
self.authenticated = True
def add_patch_to_bug(self, bug_id, patch_file_object, description, comment_text=None, mark_for_review=False):
self.authenticate()
log('Adding patch "%s" to bug %s' % (description, bug_id))
if self.dryrun:
log(comment_text)
return
self.browser.open("%sattachment.cgi?action=enter&bugid=%s" % (self.bug_server_url, bug_id))
self.browser.select_form(name="entryform")
self.browser['description'] = description
self.browser['ispatch'] = ("1",)
if comment_text:
log(comment_text)
self.browser['comment'] = comment_text
self.browser['flag_type-1'] = ('?',) if mark_for_review else ('X',)
self.browser.add_file(patch_file_object, "text/plain", "bug-%s-%s.patch" % (bug_id, timestamp()))
self.browser.submit()
def prompt_for_component(self, components):
log("Please pick a component:")
i = 0
for name in components:
i += 1
log("%2d. %s" % (i, name))
result = int(raw_input("Enter a number: ")) - 1
return components[result]
def _check_create_bug_response(self, response_html):
match = re.search("<title>Bug (?P<bug_id>\d+) Submitted</title>", response_html)
if match:
return match.group('bug_id')
match = re.search('<div id="bugzilla-body">(?P<error_message>.+)<div id="footer">', response_html, re.DOTALL)
error_message = "FAIL"
if match:
text_lines = BeautifulSoup(match.group('error_message')).findAll(text=True)
error_message = "\n" + '\n'.join([" " + line.strip() for line in text_lines if line.strip()])
raise BugzillaError("Bug not created: %s" % error_message)
def create_bug_with_patch(self, bug_title, bug_description, component, patch_file_object, patch_description, cc, mark_for_review=False):
self.authenticate()
log('Creating bug with patch description "%s"' % patch_description)
if self.dryrun:
log(bug_description)
return
self.browser.open(self.bug_server_url + "enter_bug.cgi?product=WebKit")
示例7: Bugzilla
# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import add_file [as 别名]
#.........这里部分代码省略.........
# "invalid" assume it's the login failure page.
if match and re.search("Invalid", match.group(1), re.IGNORECASE):
errorMessage = "Bugzilla login failed: %s" % match.group(1)
# raise an exception only if this was the last attempt
if attempts < 5:
log(errorMessage)
else:
raise Exception(errorMessage)
else:
self.authenticated = True
def _fill_attachment_form(self,
description,
patch_file_object,
comment_text=None,
mark_for_review=False,
mark_for_commit_queue=False,
mark_for_landing=False, bug_id=None):
self.browser['description'] = description
self.browser['ispatch'] = ("1",)
self.browser['flag_type-1'] = ('?',) if mark_for_review else ('X',)
if mark_for_landing:
self.browser['flag_type-3'] = ('+',)
elif mark_for_commit_queue:
self.browser['flag_type-3'] = ('?',)
else:
self.browser['flag_type-3'] = ('X',)
if bug_id:
patch_name = "bug-%s-%s.patch" % (bug_id, timestamp())
else:
patch_name ="%s.patch" % timestamp()
self.browser.add_file(patch_file_object,
"text/plain",
patch_name,
'data')
def add_patch_to_bug(self,
bug_id,
patch_file_object,
description,
comment_text=None,
mark_for_review=False,
mark_for_commit_queue=False,
mark_for_landing=False):
self.authenticate()
log('Adding patch "%s" to %sshow_bug.cgi?id=%s' % (description,
self.bug_server_url,
bug_id))
if self.dryrun:
log(comment_text)
return
self.browser.open("%sattachment.cgi?action=enter&bugid=%s" % (
self.bug_server_url, bug_id))
self.browser.select_form(name="entryform")
self._fill_attachment_form(description,
patch_file_object,
mark_for_review=mark_for_review,
mark_for_commit_queue=mark_for_commit_queue,
mark_for_landing=mark_for_landing,
bug_id=bug_id)
if comment_text: