def _populate_titles(self):
     kwargs = {}
     if not self._locale.fallthrough:
         kwargs['country'] = self._locale.country
     return Request('movie/{0}/alternative_titles'.format(self.id),
                    **kwargs)
Example #2
0
def searchPerson(query, adult=False):
    return PeopleSearchResult(
        Request('search/person', query=query, include_adult=adult))
Example #3
0
def searchList(query, adult=False):
    ListSearchResult(Request('search/list', query=query, include_adult=adult))
Example #4
0
File: mole.py Project: ruter/Mole
                return template(tpl_name, **tplvars)
            return result

        return wrapper

    return decorator


from template import MakoTemplate, CheetahTemplate, Jinja2Template, SimpleTALTemplate

mako_view = functools.partial(view, template_adapter=MakoTemplate)
cheetah_view = functools.partial(view, template_adapter=CheetahTemplate)
jinja2_view = functools.partial(view, template_adapter=Jinja2Template)
simpletal_view = functools.partial(view, template_adapter=SimpleTALTemplate)

from const import DEBUG, HTTP_CODES

#: A thread-save instance of :class:`Request` representing the `current` request.
request = Request()

#: A thread-save instance of :class:`Response` used to build the HTTP response.
response = Response()

#: A thread-save namepsace. Not used by Mole.
local = threading.local()

# Initialize app stack (create first empty Mole app)
# BC: 0.6.4 and needed for run()
app = default_app = AppStack()
app.push()  #---加入一个app实例
Example #5
0
    def handle_one_request(self):
        response = None
        logger = get_logger()
        try:
            self.close_connection = False
            request_line_is_valid = self.get_request_line()

            if self.close_connection:
                return

            request_is_valid = self.parse_request()
            if not request_is_valid:
                #parse_request() actually sends its own error responses
                return

            self.server.rewriter.rewrite(self)

            request = Request(self)
            response = Response(self, request)

            if not request_line_is_valid:
                response.set_error(414)
                response.write()
                return

            logger.debug("%s %s" % (request.method, request.request_path))
            handler = self.server.router.get_handler(request)

            if self.server.latency is not None:
                if callable(self.server.latency):
                    latency = self.server.latency()
                else:
                    latency = self.server.latency
                logger.warning("Latency enabled. Sleeping %i ms" % latency)
                time.sleep(latency / 1000.)

            if handler is None:
                response.set_error(404)
            else:
                try:
                    handler(request, response)
                except HTTPException as e:
                    response.set_error(e.code, e.message)
                except Exception as e:
                    if e.message:
                        err = [e.message]
                    else:
                        err = []
                        err.append(traceback.format_exc())
                    response.set_error(500, "\n".join(err))
            logger.debug(
                "%i %s %s (%s) %i" %
                (response.status[0], request.method, request.request_path,
                 request.headers.get('Referer'), request.raw_input.length))

            if not response.writer.content_written:
                response.write()

            # If we want to remove this in the future, a solution is needed for
            # scripts that produce a non-string iterable of content, since these
            # can't set a Content-Length header. A notable example of this kind of
            # problem is with the trickle pipe i.e. foo.js?pipe=trickle(d1)
            if response.close_connection:
                self.close_connection = True

            if not self.close_connection:
                # Ensure that the whole request has been read from the socket
                request.raw_input.read()

        except socket.timeout, e:
            self.log_error("Request timed out: %r", e)
            self.close_connection = True
            return
Example #6
0
    def __call__(self, http_request=None, **urlparameters):
        sapi_request = SAPIRequest(self, http_request)
        request_items = dict(sapi_request.REQUEST.items())
        request_items.update(urlparameters)

        if SIMPLEAPI_DEBUG and SIMPLEAPI_DEBUG_LEVEL == 'call':
            self.logger.info(pprint.pformat(request_items))
            self.profile_start()

        version = request_items.pop('_version', 'default')
        callback = request_items.pop('_callback', None)
        output_formatter = request_items.pop('_output', None)

        # let's activate JSONP automatically if _callback is given
        if callback and not output_formatter:
            output_formatter = 'jsonp'
        elif not output_formatter:
            output_formatter = 'json'

        input_formatter = request_items.pop('_input', 'value')
        wrapper = request_items.pop('_wrapper', 'default')
        mimetype = request_items.pop('_mimetype', None)

        input_formatter_instance = None
        output_formatter_instance = None
        wrapper_instance = None

        try:
            try:
                version = int(version)
            except (ValueError, TypeError):
                pass
            if not self.nmap.has_key(version):
                # continue with wrong version to get the formatters/wrappers
                # raise the error later!
                namespace = self.nmap['default']
            else:
                namespace = self.nmap[version]

            # check input formatter
            if input_formatter not in namespace['input_formatters']:
                raise RequestException(u'Input formatter not allowed or ' \
                                        'unknown: %s' % input_formatter)

            # get input formatter
            input_formatter_instancec = namespace['input_formatters'][
                input_formatter](sapi_request, callback)

            # check output formatter
            if output_formatter not in namespace['output_formatters']:
                raise RequestException(u'Output formatter not allowed or ' \
                                        'unknown: %s' % output_formatter)

            # get output formatter
            output_formatter_instance = namespace['output_formatters'][
                output_formatter](sapi_request, callback)

            # check wrapper
            if wrapper not in namespace['wrappers']:
                raise RequestException(u'Wrapper unknown or not allowed: %s' % \
                    wrapper)

            # get wrapper
            wrapper_instance = namespace['wrappers'][wrapper]

            # check whether version exists or not
            if not self.nmap.has_key(version):
                raise RouterException(u'Version %s not found (possible: %s)' % \
                    (version, ", ".join(map(lambda i: str(i), self.nmap.keys()))))

            request = Request(
                sapi_request=sapi_request,
                namespace=namespace,
                input_formatter=input_formatter_instancec,
                output_formatter=output_formatter_instance,
                wrapper=wrapper_instance,
                callback=callback,
                mimetype=mimetype,
                restful=self.restful,
                debug=self.debug,
                route=self,
                ignore_unused_args=self.ignore_unused_args,
            )

            # map request items to the correct names
            wi = wrapper_instance(sapi_request=sapi_request)
            request_items = wi._parse(request_items)
            if not isinstance(request_items,
                              (list, tuple, types.GeneratorType)):
                request_items = [
                    request_items,
                ]

            responses = []
            for request_item in request_items:
                # clear session (except _internal)
                sapi_request.session.clear()

                # process request
                try:
                    responses.append(request.process_request(request_item))
                except (NamespaceException, RequestException, \
                        ResponseException, RouterException, FeatureException),e:
                    response = Response(
                        sapi_request,
                        errors=e.message,
                        output_formatter=output_formatter_instance,
                        wrapper=wrapper_instance,
                        mimetype=mimetype)
                    responses.append(response)

            rm = ResponseMerger(
                sapi_request=sapi_request,
                responses=responses,
            )
            http_response = rm.build()
Example #7
0
from request import Request, Log
import re
import urllib
import urllib.parse

#Requête pour creer un compte (méthode Post) :

req = Request(ssl=True, host='www.snipes.fr', debug=True)

reponse = req.request('/registration',
                      headers={
                          'Cache-Control': 'no-cache',
                          'Connection': 'keep-alive',
                          'DNT': '1',
                          'Pragma': 'no-cache',
                          'Upgrade-Insecure-Requests': '1',
                      })

#Recupération du Token
if reponse is None:
    print("ERROR")
    exit()
matches = re.findall(
    r"<input type=\"hidden\" name=\"csrf_token\" value=\"*(.*)\"", reponse)
print("le token vaut :  {}.".format(matches[0]))
csrf = matches[0]

# Demande des parametres de creation du compte :

prenom = input("\n saisissez un prenom: ")
prenom = "dwfrm_profile_register_firstName=" + prenom
 def similar(self):
     res = MovieSearchResult(Request('movie/{0}/similar_movies'\
                                                         .format(self.id)),
                                     locale=self._locale)
     res._name = 'Similar to {0}'.format(self._printable_name())
     return res
 def lists(self):
     res = ListSearchResult(Request('movie/{0}/lists'.format(self.id)))
     res._name = "Lists containing {0}".format(self._printable_name())
     return res
Example #10
0
 def _populate_trailers(self):
     return Request('movie/{0}/trailers'.format(self.id), \
                         language=self._locale.language)
Example #11
0
 def _populate_translations(self):
     return Request('movie/{0}/translations'.format(self.id))
Example #12
0
 def _populate_releases(self):
     return Request('movie/{0}/releases'.format(self.id))
Example #13
0
 def _populate_keywords(self):
     return Request('movie/{0}/keywords'.format(self.id))
Example #14
0
 def _populate_cast(self):
     return Request('movie/{0}/casts'.format(self.id))
Example #15
0
 def __init__(self):
     self.request = Request()
     self.response = None
Example #16
0
 def _populate(self):
     return Request('collection/{0}'.format(self.id), \
                         language=self._locale.language)
Example #17
0
        # fetch the list of active servers
        client.fetchPeersList(tracker_server_address, bind_port)

        # if servers doesn't exist, use simple download
        if client.numPeerServers() == 0:
            print("No peer servers! Using default download...")
            download_object = DistributedDownloaderAndMerger(url)
            download_object.download()

        else:

            print("Peer Servers found! Distributing download...")

            # get the filesize
            req = Request()
            response = req.makeRequest(url, proxy=peerClientConfig.getProxy())
            filesize = int(response.headers['Content-Length'])
            req.closeConnection(response)
            print("peer-client filesize: {}".format(filesize))

            # get the download ranges to be assigned to each
            parts = client.numPeerServers()
            range_list = Calculation().get_download_ranges_list(
                0, filesize - 1, parts)

            # connect with each server and send them the download details
            client.connectWithPeerServers(range_list, temp_dir)

            # wait for download to complete at each server
            # except main_thread, calling join() for each thread
Example #18
0
 def _populate_images(self):
     kwargs = {}
     if not self._locale.fallthrough:
         kwargs['language'] = self._locale.language
     return Request('collection/{0}/images'.format(self.id), **kwargs)
        'r' : {'a1':[1.0], 'a2':[1.0],'u1':[0.8],'u2':[2.0]},
        'A' : {'a1': 1, 'a2': 10},
        'l_req' : {('a1','a2'): 1},
        'input_datarate' : 100,
        'chain' : "a1.(u1,u2).a2"}
        
req130 = {'UF' : {'a1':'BNG', 'a2':'CR','u1':'FW','u2':'CACHE','u3':'AV','u4':'DPI','u5':'VOPT'}, 
        'r' : {'a1':[1.0], 'a2':[1.0],'u1':[0.5],'u2':[1.0],'u3':[0.5],'u4':[1.0],'u5':[3.0]},
        'A' : {'a1': 11, 'a2': 9},
        'l_req' : {('a1','a2'): 1},
        'input_datarate' : 150,
        'chain' : "a1.(u1,u2).u3.(u4,u5).a2"}
        

if reqtype == 'mixed':
    request_list.append(Request(req140))
    request_list.append(Request(req150))
    request_list.append(Request(req160))
    request_list.append(Request(req170))
    request_list.append(Request(req171))
    request_list.append(Request(req172))
    request_list.append(Request(req180))
    request_list.append(Request(req181))
elif reqtype == 'req150':
    request_list.append(Request(req150))
elif reqtype == 'req20':
    request_list.append(Request(req20))
elif reqtype == 'req20s':
    request_list.append(Request(req20))
    request_list.append(Request(req21))
    request_list.append(Request(req22))
Example #20
0
 def _populate(self):
     return Request('list/{0}'.format(self.id))
Example #21
0
    def logfile(self, curr_host=None):
        t_time_tid = self.__init_tid()
        lineId, tid, ipid = 0, 0, 0

        for line in fileinput.input(self.log_file):
            lineId += 1
            if line[-2:] == "\r\n":  #将windows结尾格式改成Unix格式
                line = line[:-2] + "\n"
            matchs = self.rePattern.match(line)
            if matchs != None:
                ip = matchs.group("ip")
                date = matchs.group("date")
                month = matchs.group("month")
                year = matchs.group("year")
                time = matchs.group("time")
                method = matchs.group("method")
                request = matchs.group("request")
                #query = matchs.group("query")
                status = matchs.group("status")
                bytes = matchs.group("bytes")
                referer = matchs.group("referer")
                agent = matchs.group("agent")

                # ------ t_time
                oDt = Parsetime(self.db, year, month, date, time)
                logdt = str(oDt.dt['stamp'])
                if t_time_tid.get(logdt, -1) == -1:
                    oDt.new_time()
                    tid = oDt.dt['stamp']
                    t_time_tid[logdt] = tid
                else:
                    tid = t_time_tid.get(logdt)

                # ------- t_request
                #print query
                url = request
                request = url.split(' ')
                if (len(request) > 1):
                    url = request[1]
                reqjson = {
                    'tid': tid,
                    'line': lineId,
                    'ip': ip,
                    'method': method,
                    'status': status,
                    'url': url,
                    'bytes': bytes
                }
                oReq = Request(self.db, reqjson)
                oReq.do_req(tid, ip)

                # ---- t_refer
                if int(status) == 200:
                    oRefer = Referer(referer, curr_host)
                    oRefer.do_refer(self.db, tid)
                    oRefer.do_keyword(self.db, tid)  # -----keyword

                oAgent = Agent(agent)
                oAgent.do_agent(self.db, tid)
                #break
                #print lineId
        self.db.commit()
        fileinput.close()
Example #22
0
 def _populate(self):
     return Request('configuration')
Example #23
0
 def start_request(self):
     url = "http://www.baidu.com"
     yield Request(url=url, method='GET', callback=self.start_parse)
Example #24
0
            return True

    def _btnWriteClick(self, event):

        if self._validIp():
            self.path = askopenfilename(filetypes=[('All', '.*')], title="Write---->Server")
            Request().Put(self.path, self.txtIp.get())

    def _btnReadClick(self, event):

        if self._validIp():
            self.path = asksaveasfilename(filetypes=[('All', '.*')], title="Read<----Server")
            Request().Get(self.path, self.txtIp.get())

if __name__ == "__main__":
    app = InterfaceClient()
    app.title('Client TFTP')
    app.mainloop()
k(self, event):

        if self._validIp():
            self.path = askopenfilename(filetypes=[('All', '.*')], title="Write---->Server")
            Request().Put(self.path, self.txtIp.get())

    def _btnReadClick(self, event):

        if self._validIp():
            self.path = asksaveasfilename(filetypes=[('All', '.*')], title="Read<----Server")
            Request().Get(self.path, self.txtIp.get())

i
Example #25
0
 def _populate(self):
     return Request('account', session_id=self._session.sessionid)
Example #26
0
    def _btnWriteClick(self, event):

        if self._validIp():
            self.path = askopenfilename(filetypes=[('All', '.*')], title="Write---->Server")
            Request().Put(self.path, self.txtIp.get())
Example #27
0
def searchStudio(query):
    return StudioSearchResult(Request('search/company', query=query))
Example #28
0
    def _btnReadClick(self, event):

        if self._validIp():
            self.path = asksaveasfilename(filetypes=[('All', '.*')], title="Read<----Server")
            Request().Get(self.path, self.txtIp.get())
Example #29
0
def searchCollection(query, locale=None):
    return CollectionSearchResult(Request('search/collection', query=query),
                                  locale=locale)
Example #30
0
 def _populate(self):
     return Request('movie/{0}'.format(self.id), \
                         language=self._locale.language)