desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
''
def reload(self, *args, **kwds):
self.load(self.path)
'这里, 䌚盎接把文件䞊䌠到圓前目圕(self.path). 拖攟事件已经被倄理, 所以䞍䌚觊发self.app.window的拖攟劚䜜.'
def do_drag_data_received(self, drag_context, x, y, data, info, time):
if (not self.app.profile): return if (info == TargetInfo.URI_LIST): uris = data.get_uris() source_paths = util.uris_to_paths(uris) if source_paths: self.app.upload_page.upload_files(source_paths, self.path)
'打匀socket'
def get_req(self, start_size, end_size):
logger.debug(('DownloadBatch.get_req: %s, %s' % (start_size, end_size))) opener = request.build_opener() content_range = 'bytes={0}-{1}'.format(start_size, end_size) opener.addheaders = [('Range', content_range), ('User-Agent', const.USER_AGENT), ('Referer', const.PAN_REFERER)] for i in range(...
''
def destroy(self):
self.pause()
'实现了Thread的方法, 线皋启劚入口'
def run(self):
self.download()
''
def pause(self):
self.row[STATE_COL] = State.PAUSED
''
def stop(self):
self.row[STATE_COL] = State.CANCELED
'Try to connect to the given dbus services. If successful it will return a callable dbus proxy and those arguments.'
def _prepair(self):
try: sessionbus = dbus.SessionBus() systembus = dbus.SystemBus() except: return (None, None) for dbus_props in self.DBUS_SHUTDOWN.values(): try: if (dbus_props['bus'] == SESSION_BUS): bus = sessionbus else: bus = systemb...
'Call the dbus proxy to start the shutdown.'
def shutdown(self):
if self._proxy: os.sync() self._proxy(*self._args)
'因䞺Gtk没有像圚Qt䞭那么方䟿的䜿甚SQLite, 而必须将所有数据读入䞀䞪 liststore䞭才行.'
def init_db(self):
cache_path = os.path.join(Config.CACHE_DIR, self.app.profile['username']) if (not os.path.exists(cache_path)): os.makedirs(cache_path, exist_ok=True) db = os.path.join(cache_path, TASK_FILE) self.conn = sqlite3.connect(db) self.cursor = self.conn.cursor() sql = 'CREATE TABLE IF ...
''
def add_task_db(self, task):
sql = 'INSERT INTO tasks VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)' req = self.cursor.execute(sql, task) self.check_commit()
'从数据库䞭查询fsid的信息. 劂果没有的话, 就返回None'
def get_task_db(self, fs_id):
sql = 'SELECT * FROM tasks WHERE fsid=?' req = self.cursor.execute(sql, [fs_id]) if req: return req.fetchone() else: None
'圓修改数据库超过100次后, 就自劚commit数据.'
def check_commit(self, force=False):
self.commit_count = (self.commit_count + 1) if (force or (self.commit_count >= 100)): self.commit_count = 0 self.conn.commit()
''
def update_task_db(self, row):
sql = 'UPDATE tasks SET \n currsize=?, state=?, statename=?, humansize=?, percent=?\n WHERE fsid=?\n ' self.cursor.execute(sql, [row[CURRSIZE_COL], row[STATE_COL], row[STATENAME_COL], row[HUMANSI...
''
def remove_task_db(self, fs_id):
sql = 'DELETE FROM tasks WHERE fsid=?' self.cursor.execute(sql, [fs_id]) self.check_commit()
'确讀圚Liststore䞭是吊存圚这条任务. 劂果存圚, 返回TreeModelRow, 吊则就返回None'
def get_row_by_fsid(self, fs_id):
for row in self.liststore: if (row[FSID_COL] == fs_id): return row return None
''
def add_tasks(self, pcs_files, dirname=''):
def on_list_dir(info, error=None): (path, pcs_files) = info if (error or (not pcs_files)): dialog = Gtk.MessageDialog(self.app.window, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, _('Failed to scan folder to download')) dialog.format_sec...
''
def add_task(self, pcs_file, dirname=''):
if pcs_file['isdir']: return fs_id = str(pcs_file['fs_id']) row = self.get_row_by_fsid(fs_id) if row: self.app.toast(_('Task exists: {0}').format(pcs_file['server_filename'])) if (row[STATE_COL] == State.FINISHED): self.launch_app(fs_id) return if (n...
''
def scan_tasks(self, ignore_shutdown=False):
for row in self.liststore: if (len(self.workers.keys()) >= self.app.profile['concurr-download']): break if (row[STATE_COL] == State.WAITING): self.start_worker(row) if ((not self.shutdown_button.get_active()) or ignore_shutdown): return for row in self.liststo...
'䞺task新建䞀䞪后台䞋蜜线皋, 并匀始䞋蜜.'
def start_worker(self, row):
def on_worker_started(worker, fs_id): pass def on_worker_received(worker, fs_id, received, received_total): GLib.idle_add(do_worker_received, fs_id, received, received_total) def do_worker_received(fs_id, received, received_total): self.download_speed_add(received) row = None...
'停止这䞪task的后台䞋蜜线皋'
def stop_worker(self, row):
self.remove_worker(row[FSID_COL], stop=True)
''
def restart_task(self, row):
self.start_task(row)
'将任务状态讟定䞺Downloading, 劂果没有超过最倧任务数的话; 吊则将它讟定䞺Waiting.'
def start_task(self, row, scan=True):
if ((not row) or (row[STATE_COL] in RUNNING_STATES)): return row[STATE_COL] = State.WAITING row[STATENAME_COL] = StateNames[State.WAITING] self.update_task_db(row) if scan: self.scan_tasks()
''
def pause_tasks(self):
if self.first_run: return for row in self.liststore: self.pause_task(row, scan=False)
'operator - 倄理凜数'
def operate_selected_rows(self, operator):
(model, tree_paths) = self.selection.get_selected_rows() if (not tree_paths): return fs_ids = [] for tree_path in tree_paths: fs_ids.append(model[tree_path][FSID_COL]) for fs_id in fs_ids: row = self.get_row_by_fsid(fs_id) if (not row): return oper...
'Dump profile content to disk'
def on_app_shutdown(self, app):
if self.filewatcher: self.filewatcher.stop() if self.profile: self.upload_page.on_destroy() self.download_page.on_destroy()
''
def on_main_window_drag_data_received(self, window, drag_context, x, y, data, info, time):
if (not self.profile): return if (info == TargetInfo.URI_LIST): uris = data.get_uris() source_paths = util.uris_to_paths(uris) if source_paths: self.upload_page.upload_files(source_paths)
''
def on_signout_action_activated(self, action, params):
if self.profile: self.upload_page.pause_tasks() self.download_page.pause_tasks() self.show_signin_dialog(auto_signin=False)
''
def update_quota(self, quota_info, error=None):
if ((not quota_info) or (quota_info['errno'] != 0)): return used = quota_info['used'] total = quota_info['total'] used_size = util.get_human_size(used)[0] total_size = util.get_human_size(total)[0] self.capicity_label.set_text('{0} / {1}'.format(used_size, total_size)) self.pro...
''
def update_avatar(self):
def do_update_avatar(info, error=None): if (error or (not info)): logger.error(('Failed to get user avatar: %s, %s' % (info, error))) else: (uk, uname, img_path) = info self.img_avatar.set_from_file(img_path) self.img_avatar.props.too...
'所有的页面郜应该实现reload()方法.'
def reload_current_page(self, *args, **kwds):
index = self.notebook.get_current_page() self.notebook.get_nth_page(index).reload()
''
def update_clipboard(self, text):
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) clipboard.set_text(text, (-1)) self.toast(_('{0} copied to clipboard'.format(text)))
'可以䜿甚系统提䟛的Notification工具, 也可以圚窗口的最䞋方滚劚匹出'
def toast(self, text):
if self.notify: self.notify.update(Config.APPNAME, text, Config.NAME) self.notify.show()
''
def load(self, pcs_files):
self.liststore.clear() self.display_files(pcs_files)
''
def load_next(self, pcs_files):
self.display_files(pcs_files)
'文件的path郜被提取出来, 然后攟到了䞀䞪listäž­.'
def display_files(self, pcs_files):
tree_iters = [] for pcs_file in pcs_files: path = pcs_file['path'] (pixbuf, type_) = self.app.mime.get(path, pcs_file['isdir'], icon_size=self.ICON_SIZE) name = os.path.split(path)[NAME_COL] tooltip = gutil.escape(name) size = pcs_file.get('size', 0) if pcs_file['...
'获取原始的pcs文件信息'
def get_pcs_file(self, tree_path):
return json.loads(self.liststore[tree_path][PCS_FILE_COL])
''
def on_drag_data_get(self, widget, context, data, info, time):
tree_paths = self.iconview.get_selected_items() if (not tree_paths): return filelist = [] for tree_path in tree_paths: filelist.append({'path': self.liststore[tree_path][PATH_COL], 'newname': self.liststore[tree_path][NAME_COL]}) filelist_str = json.dumps(filelist) if (info == Ta...
''
def on_drag_data_received(self, widget, context, x, y, data, info, time):
if (not data): return tree_path = self.iconview.get_path_at_pos(x, y) if (tree_path is None): return target_path = self.liststore[tree_path][PATH_COL] is_dir = self.liststore[tree_path][ISDIR_COL] if ((not is_dir) or (info != TargetInfo.PLAIN_TEXT)): return filelist_s...
''
def launch_app(self, tree_path):
file_type = self.liststore[tree_path][TYPE_COL] app_infos = Gio.AppInfo.get_recommended_for_type(file_type) if app_infos: self.launch_app_with_app_info(app_infos[0]) else: pass
'创建犻线䞋蜜任务, 䞋蜜选䞭的BT种子.'
def on_cloud_download_item_activated(self, menu_item):
tree_paths = self.iconview.get_selected_items() if (not tree_paths): return self.app.cloud_page.add_cloud_bt_task(self.liststore[tree_paths[0]][PATH_COL])
''
def on_download_to_activated(self, menu_item):
tree_paths = self.iconview.get_selected_items() if (not tree_paths): return dialog = Gtk.FileChooserDialog(_('Save to...'), self.app.window, Gtk.FileChooserAction.SELECT_FOLDER, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK)) response = dialog.run() if (res...
''
def on_props_activated(self, menu_item):
tree_paths = self.iconview.get_selected_items() if (not tree_paths): dialog = FolderPropertyDialog(self, self.app, self.parent.path) dialog.run() dialog.destroy() else: for tree_path in tree_paths: pcs_file = self.get_pcs_file(tree_path) dialog = Prope...
''
def on_drag_data_received(self, widget, context, x, y, data, info, time):
if (not data): return (bx, by) = self.iconview.convert_widget_to_bin_window_coords(x, y) selected = Gtk.TreeView.get_path_at_pos(self.iconview, bx, by) if (not selected): return tree_path = selected[0] if (tree_path is None): return target_path = self.liststore[tree_p...
'圓修改数据库超过50次后, 就自劚commit数据.'
def check_commit(self, force=False):
self.commit_count = (self.commit_count + 1) if (force or (self.commit_count >= 50)): self.commit_count = 0 self.conn.commit()
'向数据库䞭写入䞀䞪新的任务记圕, 并返回它的fid'
def add_task_db(self, task, force=True):
sql = 'INSERT INTO upload (\n name, source_path, path, size, curr_size, state, state_name,\n human_size, percent, tooltip, threshold)\n VALUES (?, ?, ?, ?, ?, ?, ?, ...
''
def add_slice_db(self, fid, slice_end, md5):
sql = 'INSERT INTO slice VALUES(?, ?, ?)' self.cursor.execute(sql, (fid, slice_end, md5)) self.check_commit()
'从数据库䞭查询source_path的信息. 劂果没有的话, 就返回None'
def get_task_db(self, source_path):
sql = 'SELECT * FROM upload WHERE source_path=?' req = self.cursor.execute(sql, [source_path]) if req: return req.fetchone() else: None
'从数据库䞭取埗fid的所有分片. 返回的是䞀䞪list, 里面是按顺序排奜的md5的倌'
def get_slice_db(self, fid):
sql = 'SELECT md5 FROM slice WHERE fid=?' req = self.cursor.execute(sql, [fid]) if req: return [r[0] for r in req] else: return None
''
def update_task_db(self, row, force=False):
sql = 'UPDATE upload SET \n curr_size=?, state=?, state_name=?, human_size=?, percent=?\n WHERE fid=?\n ' self.cursor.execute(sql, [row[CURRSIZE_COL], row[STATE_COL], row[STATENAME_COL], row[HUMA...
''
def remove_task_db(self, fid, force=False):
self.remove_slice_db(fid) sql = 'DELETE FROM upload WHERE fid=?' self.cursor.execute(sql, [fid]) self.check_commit(force=force)
''
def remove_slice_db(self, fid):
sql = 'DELETE FROM slice WHERE fid=?' self.cursor.execute(sql, [fid]) self.check_commit()
''
def add_file_task(self, dir_name=None):
file_dialog = Gtk.FileChooserDialog(_('Choose Files..'), self.app.window, Gtk.FileChooserAction.OPEN, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK)) file_dialog.set_modal(True) file_dialog.set_select_multiple(True) file_dialog.set_default_response(Gtk.ResponseType.OK)...
''
def add_folder_task(self, dir_name=None):
folder_dialog = Gtk.FileChooserDialog(_('Choose Folders..'), self.app.window, Gtk.FileChooserAction.SELECT_FOLDER, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK)) folder_dialog.set_modal(True) folder_dialog.set_select_multiple(True) folder_dialog.set_default_response(G...
'source_path - 本地文件的绝对路埄 dir_name - 文件圚服务噚䞊的父目圕, 劂果䞺None的话, 䌚匹出䞀䞪'
def upload_files(self, source_paths, dir_name=None):
def scan_folders(folder_path): file_list = os.listdir(folder_path) source_paths = [os.path.join(folder_path, f) for f in file_list] self.upload_files(source_paths, os.path.join(dir_name, os.path.split(folder_path)[1])) self.check_first() if (not dir_name): folder_dialog = Fol...
''
def upload_file(self, source_path, dir_name):
row = self.get_task_db(source_path) (source_dir, filename) = os.path.split(source_path) path = os.path.join(dir_name, filename) size = os.path.getsize(source_path) total_size = util.get_human_size(size)[0] tooltip = gutil.escape(_('From {0}\nTo {1}').format(source_path, path)) if (size...
'将任务状态讟定䞺Uploading, 劂果没有超过最倧任务数的话; 吊则将它讟定䞺Waiting.'
def start_task(self, row, scan=True):
if (row[STATE_COL] in RUNNING_STATES): self.scan_tasks() return row[STATE_COL] = State.WAITING row[STATENAME_COL] = StateNames[State.WAITING] self.update_task_db(row) if scan: self.scan_tasks()
''
def pause_tasks(self):
if self.first_run: return for row in self.liststore: self.pause_task(row, scan=False)
''
def pause_task(self, row, scan=True):
if (row[STATE_COL] == State.UPLOADING): self.remove_worker(row[FID_COL], stop=False) if (row[STATE_COL] in (State.UPLOADING, State.WAITING)): row[STATE_COL] = State.PAUSED row[STATENAME_COL] = StateNames[State.PAUSED] self.update_task_db(row) if scan: self.sca...
''
def remove_task(self, row, scan=True):
if (row[STATE_COL] == State.UPLOADING): self.remove_worker(row[FID_COL], stop=True) self.remove_task_db(row[FID_COL]) tree_iter = row.iter if tree_iter: self.liststore.remove(tree_iter) if scan: self.scan_tasks()
'operator - 倄理凜数'
def operate_selected_rows(self, operator):
(model, tree_paths) = self.selection.get_selected_rows() if (not tree_paths): return fids = [] for tree_path in tree_paths: fids.append(model[tree_path][FID_COL]) for fid in fids: row = self.get_row_by_fid(fid) if row: operator(row)
'parent - UploadPage row - UploadPage.liststore䞭的䞀䞪记圕'
def __init__(self, parent, row, cookie, tokens):
threading.Thread.__init__(self) GObject.GObject.__init__(self) self.daemon = True self.parent = parent self.cookie = cookie self.tokens = tokens self.upload_mode = self.parent.app.profile['upload-mode'] self.row = row[:]
''
def upload(self):
info = pcs.upload(self.cookie, self.row[SOURCEPATH_COL], self.row[PATH_COL], self.upload_mode) if info: self.emit('uploaded', self.row[FID_COL]) else: self.emit('network-error', self.row[FID_COL])
''
def rapid_upload(self):
info = pcs.rapid_upload(self.cookie, self.tokens, self.row[SOURCEPATH_COL], self.row[PATH_COL], self.upload_mode) if (info and info['md5'] and info['fs_id']): self.emit('uploaded', self.row[FID_COL]) else: self.slice_upload()
''
def slice_upload(self):
self.is_slice_upload = True fid = self.row[FID_COL] slice_start = self.row[CURRSIZE_COL] slice_end = self.row[CURRSIZE_COL] file_size = os.path.getsize(self.row[SOURCEPATH_COL]) if (file_size < slice_start): self.emit('disk-error', fid) return elif ((file_size == slice_start)...
'只蟓出cookie的key-valueå­—äž². 比劂: HISTORY=21341; PHPSESSION=3289012u39jsdijf28; token=233129'
def header_output(self):
result = [] for key in self.keys(): result.append(((key + '=') + self.get(key).value)) return '; '.join(result)
'获取䞀郚分cookie, 并将它蟓出䞺字笊䞲'
def sub_output(self, *keys):
result = [] for key in keys: if self.get(key): result.append(((key + '=') + self.get(key).value)) return '; '.join(result)
'读取倚䞪以字笊䞲圢匏存攟的cookie.'
def load_list(self, raw_items):
if (not raw_items): return for item in raw_items: self.load(item)
''
def do_response(self, response_id):
if (response_id != Gtk.ResponseType.OK): return filelist = [] for row in self.rows: if (row[1].get_text() == row[2].get_text()): continue filelist.append({'path': row[0], 'newname': row[2].get_text()}) if (len(filelist) == 0): return pcs.rename(self.app.co...
'初始化BT种子查询对话框. source_url - 劂果是BT种子的话, 就是种子的绝对路埄. 劂果是磁铟的话, 就是以magent:匀倎的磁铟铟接.'
def __init__(self, parent, app, title, source_url, save_path):
super().__init__(title, app.window, Gtk.DialogFlags.MODAL, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK)) self.app = app self.source_url = source_url self.save_path = save_path self.set_default_response(Gtk.ResponseType.OK) self.set_default_size(520, 480) sel...
'圚调甚dialog.run()之前先调甚这䞪凜数来获取数据'
def request_data(self):
def on_tasks_received(info, error=None): if (error or (not info)): logger.error(('BTBrowserDialog.on_tasks_received: %s, %s.' % (info, error))) return if ('magnet_info' in info): tasks = info['magnet_info'] elif ('torrent_info' in info): ...
'返回选䞭芁䞋蜜的文件的猖号及sha1倌, 从1匀始计数.'
def get_selected(self):
selected_idx = [] for (i, row) in enumerate(self.liststore): if row[CHECK_COL]: selected_idx.append((i + 1)) return (selected_idx, self.file_sha1)
''
def load_next(self):
self.page += 1 self.load_url()
''
def load_url(self):
def on_load_url(filelist, error=None): self.url_entry.props.secondary_icon_name = REFRESH_ICON if (timestamp != self.url_entry.timestamp): logger.debug('SharePage.load_url, dirname not match, ignored') return if (error or (not filelist)): self....
''
def get_mime(self, path, isdir):
if isdir: file_type = FOLDER else: file_type = mimetypes.guess_type(path)[0] if (not file_type): file_type = UNKNOWN return file_type
'path - 文件的路埄, 可以包括绝对路埄, 也可以是文件名. isdir - 是吊䞺䞀䞪目圕. icon_size - 囟标的倧小, 劂果是星瀺圚IconView侭的, 48就可以; 劂果是星瀺圚TreView的话, 可以甚Gtk.IconSize.MENU @return 䌚返回䞀䞪Pixbuf以象, 和这䞪文件的类型(MIME)'
def get(self, path, isdir, icon_size=ICON_SIZE):
file_type = self.get_mime(path, isdir) key = (file_type, icon_size) if (key in self._data): return (self._data.get(key), file_type) themed_icon = Gio.content_type_get_icon(file_type) icon_names = themed_icon.to_string().split(' ')[2:] icon_info = self.app.icon_theme.choose_icon(icon_n...
''
def get_path(self):
(model, tree_iter) = self.selection.get_selected() if (not tree_iter): return '/' else: return model[tree_iter][PATH_COL]
'Log with level debug.'
def debug(self, txt):
self(txt, 'debug')
'Log with level info.'
def info(self, txt):
self(txt, 'info')
'Log with level alert. Alerts have the same urgency as info, but signals to interctive tools that the user\'s attention should be drawn to the output even if they\'re not currently looking at the event log.'
def alert(self, txt):
self(txt, 'alert')
'Log with level warn.'
def warn(self, txt):
self(txt, 'warn')
'Log with level error.'
def error(self, txt):
self(txt, 'error')
'onclick is called on click with the tab offset as argument'
def __init__(self, offset, content, attr, onclick):
p = urwid.Text(content, align='center') p = urwid.Padding(p, align='center', width=('relative', 100)) p = urwid.AttrWrap(p, attr) urwid.WidgetWrap.__init__(self, p) self.offset = offset self.onclick = onclick
'We are just about to push a window onto the stack.'
def layout_pushed(self, prev):
self.helpctx = prev.keyctx self.show()
'vspace: how much vertical space to keep clear'
def __init__(self, master, name, vals, vspace):
(cols, rows) = master.ui.get_cols_rows() self.ge = grideditor.OptionsEditor(master, name, vals) super().__init__(urwid.AttrWrap(urwid.LineBox(urwid.BoxAdapter(self.ge, (rows - vspace)), title=name), 'background')) self.width = math.ceil((cols * 0.8))
'Returns the object responding to key input. Usually self, but may be a wrapped object.'
def key_responder(self):
return self
'The view focus has changed. Layout objects should implement the API rather than directly subscribing to events.'
def focus_changed(self):
pass
'The view list has changed.'
def view_changed(self):
pass
'We are just about to pop a window off the stack, or exit an overlay.'
def layout_popping(self):
pass
'We have just pushed a window onto the stack.'
def layout_pushed(self, prev):
pass
'_testing: disables reloading of the lookup table to make testing possible.'
def __init__(self, _testing=False):
(self.lookup, self.offset) = (None, None) self.final = None self._testing = _testing
'Returns the next completion for txt, or None if there is no completion.'
def complete(self, txt):
path = os.path.expanduser(txt) if (not self.lookup): if (not self._testing): self.lookup = [] if os.path.isdir(path): files = glob.glob(os.path.join(path, '*')) prefix = txt else: files = glob.glob((path + '*')) ...
'Args: fields: (optional) list of ``(name, value)`` header byte tuples, e.g. ``[(b"Host", b"example.com")]``. All names and values must be bytes. **headers: Additional headers to set. Will overwrite existing values from `fields`. For convenience, underscores in header names will be transformed to dashes - this behaviou...
def __init__(self, fields=(), **headers):
super().__init__(fields) for (key, value) in self.fields: if ((not isinstance(key, bytes)) or (not isinstance(value, bytes))): raise TypeError('Header fields must be bytes.') headers = {_always_bytes(name).replace('_', '-'): _always_bytes(value) for (name, value) in headers.i...
'Like :py:meth:`get`, but does not fold multiple headers into a single one. This is useful for Set-Cookie headers, which do not support folding. See also: https://tools.ietf.org/html/rfc7230#section-3.2.2'
def get_all(self, name):
name = _always_bytes(name) return [_native(x) for x in super().get_all(name)]
'Explicitly set multiple headers for the given key. See: :py:meth:`get_all`'
def set_all(self, name, values):
name = _always_bytes(name) values = [_always_bytes(x) for x in values] return super().set_all(name, values)
'Replaces a regular expression pattern with repl in each "name: value" header line. Returns: The number of replacements made.'
def replace(self, pattern, repl, flags=0, count=0):
if isinstance(pattern, str): pattern = strutils.escaped_str_to_bytes(pattern) if isinstance(repl, str): repl = strutils.escaped_str_to_bytes(repl) pattern = re.compile(pattern, flags) replacements = 0 flag_count = (count > 0) fields = [] for (name, value) in self.fields: ...
':param fail_early: If true, a SocksError will be raised if the first byte does not indicate socks5.'
@classmethod def from_file(cls, f, fail_early=False):
(ver, nmethods) = struct.unpack('!BB', f.safe_read(2)) client_greeting = cls(ver, []) if fail_early: client_greeting.assert_socks5() client_greeting.methods.frombytes(f.safe_read(nmethods)) return client_greeting
'Raises: ValueError, if the content-encoding is invalid.'
def make_environ(self, flow, errsoc, **extra):
path = strutils.always_str(flow.request.path, 'latin-1') if ('?' in path): (path_info, query) = strutils.always_str(path, 'latin-1').split('?', 1) else: path_info = path query = '' environ = {'wsgi.version': (1, 0), 'wsgi.url_scheme': strutils.always_str(flow.request.scheme, 'lat...
'Make a best-effort attempt to write an error page. If headers are already sent, we just bung the error into the page.'
def error_page(self, soc, headers_sent, s):
c = '\n <html>\n <h1>Internal Server Error</h1>\n <pre>{err}"</pre>\n </html>\n ...
'A WebSocket frame contains an initial length_code, and an optional extended length code to represent the actual length if length code is larger than 125'
@classmethod def _make_length_code(self, length):
if (length <= 125): return length elif ((length >= 126) and (length <= 65535)): return 126 else: return 127