Beispiel #1
0
def handle(request):

    # URL Parsing
    s = "api."
    if 'project' in request.match_info:
        p = re.sub('[^0-9a-zA-Z]+', '', request.match_info['project'])
        s += p + "."
    if 'module' in request.match_info:
        p = re.sub('[^0-9a-zA-Z]+', '', request.match_info['module'])
        s += p + "."
    if 'action' in request.match_info:
        p = re.sub('[^0-9a-zA-Z]+', '', request.match_info['action'])
        s += p
    if verbose_logging:
        print("Incoming request - " + str(request.raw_path))

    # Session loading
    if "cookie" in request.headers and "AIOHTTP_SESSION" in request.headers[
            "cookie"]:
        cookies = request.headers.getall("cookie")[0]
        aiocookie = re.search("AIOHTTP_SESSION=([0-9a-z]{32})", cookies)
        if aiocookie:
            session = sessions.Session(aiocookie.group(1))
            if verbose_logging:
                print("Session ID - " + session.id)
        else:
            session = sessions.Session()
            if verbose_logging:
                print("New Session with ID - " + session.id)
    else:
        session = sessions.Session()
        if verbose_logging:
            print("New Session with ID - " + session.id)

    # Response building
    try:
        module = importlib.import_module(s)
        arguments = url.parse(request.GET, module.arguments)
        response = yield from module.process(session, arguments)
        headers = response.get('headers', {})
        if session.is_new_session:
            headers.update({"Set-Cookie": "AIOHTTP_SESSION=" + session.id})
        if 'json' in response:
            # Dump to json if the module wants to return json
            return respond(headers=headers,
                           status=response.get('status', 200),
                           text=json.dumps(response.get("json", "")),
                           content_type="application/json")
        else:
            return respond(headers=headers,
                           status=response.get('status', 200),
                           text=response.get("text", ""))
    except ImportError:
        return respond(status=404, text="Page does not exist")
    except Exception as e:
        s = str(e.args) if verbose_errors else "No verbose errors."
        return respond(status=500, text="Error while querying data.\n" + s)
def request(method, url, **kwargs):
    """Constructs and sends a :class:`Request <Request>`.
    Returns :class:`Response <Response>` object.

    :param method: method for the new :class:`Request` object.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
    :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
    :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
    :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
    :param files: (optional) Dictionary of 'name': file-like-objects (or {'name': ('filename', fileobj)}) for multipart encoding upload.
    :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
    :param timeout: (optional) Float describing the timeout of the request.
    :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
    :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
    :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.
    :param stream: (optional) if ``False``, the response content will be immediately downloaded.
    :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.

    Usage::

      >>> import requests
      >>> req = requests.request('GET', 'http://httpbin.org/get')
      <Response [200]>
    """

    session = sessions.Session()
    return session.request(method=method, url=url, **kwargs)
Beispiel #3
0
 def get(self):
     sess = sessions.Session()
     maker=sess['maker']
     sess['maker']=hangman.genSecret()
     sess['guesscode']=[]
     sess['wrong']=0
             display="Guess"        
Beispiel #4
0
def _subscribe():
    subscribe = set(flask.request.values.getlist("list"))
    session = sessions.Session(app.config)
    maillists = mailman.MailLists(
        app.config,
        email=session['email'],
        hsmember=session['member'],
    )
    # XXX: iterate through the known mail lists, not through what user has
    # requested
    for l in maillists.lists():
        if l['name'] in subscribe and not l['subscribed']:
            # user requested subscription of this list and is not already
            # subscribed
            # NOTE: subscriptions for members only is enforced in
            # maillists.subscribe()
            maillists.subscribe(l['name'])
        elif l['name'] not in subscribe and l['subscribed']:
            # user requested cease subscription and is subscribed
            maillists.unsubscribe(l['name'])
        else:
            # otherwise subscription status is unchanged
            pass
    session.add_message(u"Subskrypcje uaktualnione.")
    session.save()
    return flask.redirect(flask.url_for('panel'))
Beispiel #5
0
def _account_update():
    session = sessions.Session(app.config)
    account = accounts.Account(app.config, session['user'])

    # NOTE: ldap_update() calls in this manner would be highly ineffective,
    # but fortunately HTML forms send these fields one at a request, so it's
    # generally OK

    full_name = flask.request.values.get("full_name", "")
    if full_name != "":
        session['full_name'] = account['cn'] = full_name
        session.add_message(u"Imię/nazwisko zmienione.")

    email = flask.request.values.get("email", "")
    if email != "":
        token = account.request_email_change(email)
        url = flask.url_for('change_email', token=token, _external=True)
        values = {
            'confirmation_link': url,
            'nick': account['uid'],
            'email_from': app.config['EMAIL_FROM'],
            'email_to': email,
        }
        email_body = flask.render_template('email_change.txt', **values)

        smtp = fsmtp.SMTP(app.config)
        smtp.send_email(email, email_body)
        session.add_message(u"Wiadomość z linkiem potwierdzającym zmianę" \
                            u" wysłana.")

    password = flask.request.values.get("password", "")
    password2 = flask.request.values.get("password_repeated", "")
    if password != "" or password2 != "":
        if password != password2:
            message = u'Hasła się nie zgadzają.'
            title = u'Błąd ustawiania hasła'
            link = {
                'url': flask.url_for('panel'),
                'description': u'Powrót',
            }
            return flask.render_template('message.html',
                                         message=message,
                                         title=title,
                                         link=link)
        account.set_password(password)
        session.add_message(u"Hasło zmienione.")

    account.save()
    session.save()

    # TODO: some message maybe?
    return flask.redirect(flask.url_for('panel'))
Beispiel #6
0
def logout():
    session = sessions.Session(app.config)
    session.delete()
    message = 'Wylogowano.'
    title = 'Wylogowano'
    link = {
        'url': flask.url_for('index'),
        'description': u'Zaloguj ponownie',
    }
    return flask.render_template('message.html',
                                 message=message,
                                 title=title,
                                 link=link)
Beispiel #7
0
def _panel():
    session = sessions.Session(app.config)
    maillists = mailman.MailLists(
        app.config,
        email=session['email'],
        hsmember=session['member'],
    )
    messages = session.pop_messages()
    if messages is not None:
        session.save()
    return flask.render_template('panel.html',
                                 account=session,
                                 maillists=maillists,
                                 messages=messages)
Beispiel #8
0
 def get(self):
     sess = sessions.Session()
     sess['maker']=hangman.genSecret()
     maker=sess['maker']
     sess['wrong']=0
     sess['guesscode']=[]
     display="Guess next letter"
     secretCode=""
     while len(secretCode)<len(maker):
         secretCode=secretCode+'*'
     sess['secretCode']=secretCode
     image="/images/1.png"
     template_values={'picHang':image, 'display':display, 'Code':str(maker),'secretCode':str(secretCode)}
     path = os.path.join(os.path.dirname(__file__),'index.html')
     self.response.out.write(template.render(path,template_values))
Beispiel #9
0
 def get(self):
     user = users.get_current_user()
     nickname = user.nickname()
     sess = sessions.Session()
     TeamA = self.request.get('TeamA')
     TeamB = self.request.get('TeamB')
     sess['teamA'] = TeamA
     previous = db.GqlQuery("Select * from Result")
     # set up template value
     template_values = {
         'TeamA': TeamA,
         'TeamB': TeamB,
         'user': nickname,
         'previous': previous
     }
     path = os.path.join(os.path.dirname(__file__), 'input.html')
     self.response.out.write(template.render(path, template_values))
Beispiel #10
0
 def __init__(self, **kwargs):
     """
     @param kwargs: Keyword arguments.
         - B{proxy} - An http proxy to be specified on requests.
              The proxy is defined as {protocol:proxy,}
                 - type: I{dict}
                 - default: {}
         - B{timeout} - Set the url open timeout (seconds).
                 - type: I{float}
                 - default: 90
     """
     Transport.__init__(self)
     self.sslverify = kwargs.pop("sslverify")
     Unskin(self.options).update(kwargs)
     self.cookiejar = CookieJar()
     self.proxy = {}
     self.urlopener = None
     self.session = sessions.Session()
     self.session.proxies = self.proxy
     self.session.verify=self.sslverify
Beispiel #11
0
 def handle(self):
     if WELCOME_SHOW:
         try:
             welcome = open(WELCOME_FILE, mode='r')
             for line in welcome:
                 self.request.send(line + "\r")
             welcome.close()
         except IOError:
             self.request.send("")
     session = sessions.Session(self)
     alive = 1
     while session.logged:
         message = session.Input()
         if not session.logged:
             alive = 0
             break
         if not message: break
         session.Process(message)
     if (alive == 1):
         #save user details
         if session.login: session.Logout()
         del (session)
Beispiel #12
0
 def new_view(*args, **kwargs):
     session = sessions.Session(app.config)
     if session['user'] is None:
         return flask.redirect(flask.url_for('index'))
     else:
         return view(*args, **kwargs)
Beispiel #13
0
def login():
    if 'reset_password' in flask.request.values:
        try:
            account = accounts.Account(app.config,
                                       flask.request.values['nick'])
        except accounts.NoSuchUserError:
            title = u"Resetowanie hasła"
            message = u"Nie ma takiego użytkownika." \
                      u" Czy chcesz się zarejestrować?"
            link = {
                'url': flask.url_for('index'),
                'description': u'Powrót do strony głównej',
            }
            return flask.render_template('message.html',
                                         message=message,
                                         title=title,
                                         link=link)
        token = account.request_reset_password()
        url = flask.url_for('reset_password', token=token, _external=True)
        values = {
            'reset_password_link': url,
            'nick': account['uid'],
            'email_from': app.config['EMAIL_FROM'],
            'email_to': account['contactMail'][0],
        }
        email_body = flask.render_template('email_reset_password.txt',
                                           **values)

        smtp = fsmtp.SMTP(app.config)
        smtp.send_email(account['contactMail'][0], email_body)

        title = u"Resetowanie hasła"
        message = u"E-mail dla resetowania hasła został wysłany."
        link = {
            'url': flask.url_for('index'),
            'description': u'Powrót do strony głównej',
        }
        return flask.render_template('message.html',
                                     message=message,
                                     title=title,
                                     link=link)

    try:
        username = flask.request.values['nick']
        password = flask.request.values.get('password')
        account = accounts.Account(app.config, username, password)
    except accounts.AuthenticationError:
        title = u"Błąd logowania"
        message = u"Nieprawidłowy login lub błędne hasło."
        link = {
            'url': flask.url_for('index'),
            'description': u'Powrót',
        }
        return flask.render_template('message.html',
                                     message=message,
                                     title=title,
                                     link=link)

    session = sessions.Session(app.config)
    session['dn'] = account['dn']
    session['user'] = account['uid']
    session['full_name'] = account['cn']
    session['member'] = account.field('isHSWroMember', default=False)
    session['verified'] = account.field('isVerified', default=False)
    session['email'] = account.field('contactMail', [None])[0]
    session['hs_emails'] = account.field('mail', [])
    session.save()

    response = flask.make_response(flask.redirect(flask.url_for('panel')))
    (cookie_name, cookie_value) = session.cookie()
    response.set_cookie(cookie_name, cookie_value)

    return response
Beispiel #14
0
        errors = "Post must have your name and an actual comment."
        return bottle.template(
            "entry_template",
            dict(post=post, username=username, errors=errors, comment=comment))

    else:

        posted.add_postcomment(permalink, name, email, body)

        bottle.redirect("/post/" + permalink)


@bottle.get('/authorspecific')
def author_post():
    cookie = bottle.request.get_cookie("session")
    author = session.get_sessionusername(cookie)
    authorpost = posted.get_post_by_author(author)
    return bottle.template('homepage', dict(myposts=authorpost,
                                            username=author))


connection_string = "mongodb://localhost"
connection = pymongo.MongoClient(connection_string)
database = connection.blog

user = users.User(database)
session = sessions.Session(database)
posted = posts.BlogPost(database)

bottle.debug(True)
bottle.run(host='localhost', port=8080)
Beispiel #15
0
    "Server environment for coordinating media management and streaming on behalf of LiveCloud apps."
)

cli.add_argument("-i",
                 "--handlers",
                 help="choose input and output handlers for interfacing with",
                 dest="handlers",
                 type=str,
                 nargs="*",
                 choices=list(handlerNames.keys()),
                 default="tty")

arguments = cli.parse_args()

handlerArguments = [arguments.handlers] if isinstance(
    arguments.handlers, str) else arguments.handlers

handlers = []
inputHandlers = []
printHandlers = []

for i in range(0, len(handlerArguments)):
    handlers.append(handlerNames[handlerArguments[i]].Handler())

    inputHandlers.append(handlers[-1].handleInput)
    printHandlers.append(handlers[-1].handlePrint)

rootSession = sessions.Session(inputHandlers=inputHandlers,
                               printHandlers=printHandlers)

rootSession.start()
Beispiel #16
0
    def get(self):
        sess=sessions.Session()
        maker=sess['maker']
        secretCode=sess['secretCode']    
        wrong=sess['wrong']    
        guesscode=sess['guesscode']
        nowGuess=str(self.request.get('letter'))
        if maker==None:
            maker=hangman.genSecret()
            sess['maker']=maker
        i=0
        match=False
        while i<len(maker):
            if nowGuess in guesscode:
                display="You have already guessed that letter..."
                match=True
            elif nowGuess==maker[i]:
                secretCode=secretCode[0:i]+nowGuess+secretCode[i+1:len(secretCode)]
                sess['secretCode']=secretCode
                match=True
            i=i+1
        if not match:    
            wrong=wrong+1
        if wrong==0:
            image='/images/1.png'        
        if wrong==1:
            image='/images/2.png'
        if wrong==2:
            image='/images/3.png'
        if wrong==3:
            image='/images/4.png'
        if wrong==4:
            image='/images/5.png'
        if wrong==5:
            image='/images/6.png'
        if wrong==6:
            image='/images/7.png'
        if wrong==7:
            image='/images/8.png'
        if wrong==8:
            image='/images/9.png'
        if wrong==9:
            image='/images/10.png'
        if wrong==10:
            image='/images/11.png'
            

        sess['wrong']=wrong
                #win        
        if maker==secretCode:
            display="You Won! Congratulations!"
        elif wrong==10:
            display="YOU KILLED YOURSELF!"
            secretCode=maker
        elif nowGuess in guesscode:
            display="DUPLICATE LETTER. Guess Again."
        else:
            guesscode.append(nowGuess)
            sess['guesscode']=guesscode        
            display="Guess your next letter: "
        template_values= {'guess':str(guesscode), 'Code':str(maker), 'guesscode':guesscode, 'display':display, 'picHang':image, 'secretCode':str(secretCode)}


        path = os.path.join(os.path.dirname(__file__),'index.html')
        self.response.out.write(template.render(path,template_values))
Beispiel #17
0
def change_email(token):
    try:
        account = accounts.Account(app.config, change_email=token)
    except accounts.InvalidTokenError:
        title = u"Resetowanie hasła nieudane"
        message = u"Nieprawidłowy link do resetowania hasła."
        return flask.render_template('message.html',
                                     message=message,
                                     title=title)
    except accounts.NoSuchUserError:
        title = u"Resetowanie hasła nieudane"
        message = u"Użytkownik nie istnieje."
        return flask.render_template('message.html',
                                     message=message,
                                     title=title)

    nick = account['uid']
    old_email = account.old_field('contactMail')[0]
    new_email = account['contactMail'][0]

    if flask.request.method == "GET":
        return flask.render_template('change_email.html',
                                     token=token,
                                     nick=nick,
                                     new_email=new_email,
                                     old_email=old_email)

    # flask.request.method == "POST"

    # `account' is already prepared to update contactMail field
    account.save()
    account.clear_email_change_request()

    if flask.request.values.get("migrate") == "true":
        # XXX: lie about membership, because subscription requests for
        # non-members are silently ignored
        # FIXME: make it so mailman.MailLists doesn't need to know about
        # HS:Wro membership
        old_lists = mailman.MailLists(app.config, email=old_email)
        new_lists = mailman.MailLists(
            app.config,
            email=new_email,
            hsmember=True,
        )
        for ol in old_lists.lists():
            if ol['subscribed']:
                old_lists.unsubscribe(ol['name'])
                # if new e-mail was already subscribed to this list, this will
                # be a little excessive, but it doesn't matter
                new_lists.subscribe(ol['name'])

    session = sessions.Session(app.config)
    if len(session) > 0:
        session['email'] = account['contactMail'][0]
        session.add_message(u"Adres e-mail uaktualniony.")
        session.save()
        return flask.redirect(flask.url_for('panel'))
    else:
        title = u"Adres e-mail zmieniony"
        message = u"Adres e-mail uaktualniony."
        link = {
            'url': flask.url_for('index'),
            'description': u'Zaloguj',
        }
        return flask.render_template('message.html',
                                     message=message,
                                     title=title,
                                     link=link)
Beispiel #18
0
def index():
    session = sessions.Session(app.config)
    if len(session) > 0:
        return flask.redirect(flask.url_for('panel'))
    return flask.render_template('index.html')
Beispiel #19
0
 def get(self):
     user = users.get_current_user()
     logout = users.create_logout_url('/')
     nickname = user.nickname()
     sess = sessions.Session()
     TeamA = sess['teamA']
     #calculations for stats
     PPG1 = self.request.get('PPG1')
     PA1 = self.request.get('PA1')
     FGP1 = self.request.get('FGP1')
     PPG2 = self.request.get('PPG2')
     PA2 = self.request.get('PA2')
     FGP2 = self.request.get('FGP1')
     PPG1 = float(PPG1)
     PA1 = float(PA1)
     FGP1 = float(FGP1)
     PPG2 = float(PPG2)
     PA2 = float(PA2)
     FGP2 = float(FGP2)
     X = handicapfunc.calcPoints(PPG1, PA1, FGP1)
     Y = handicapfunc.calcPoints(PPG2, PA2, FGP2)
     X = float(X)
     Y = float(Y)
     winStat = handicapfunc.winStat(X, Y)
     #calculations for ratings
     CA = self.request.get('CA')
     GI = self.request.get('GI')
     SA = self.request.get('SA')
     HC = self.request.get('HC')
     BP = self.request.get('BP')
     I = self.request.get('I')
     TE = self.request.get('TE')
     TM = self.request.get('TM')
     SI = self.request.get('SI')
     HH = self.request.get('HH')
     CA = float(CA)
     GI = float(GI)
     SA = float(SA)
     HC = float(HC)
     BP = float(BP)
     I = float(I)
     TE = float(TE)
     TM = float(TM)
     SI = float(SI)
     HH = float(HH)
     winRank = handicapfunc.winRank(CA, GI, SA, HC, BP, I, TE, TM, SI, HH)
     Final1 = (winRank + winStat) / 2
     Final2 = round(Final1, 2)
     Final = math.fabs(Final2)
     Line1 = handicapfunc.getLine(Final)
     Line = '%.1f' % Line1
     result = model.Result()
     LineString = TeamA + ' ' + Line
     result.line = str(LineString)
     result.put()
     previous = db.GqlQuery("Select * from Result")
     #set up template value
     template_values = {
         'WinPercentStat': winStat,
         'WinPercentRank': winRank,
         'WinPercentFinal': Final,
         'Line': Line,
         'previous': previous,
         'final': Final,
         'TeamA': TeamA,
         'user': nickname,
         'logout': logout
     }
     path = os.path.join(os.path.dirname(__file__), 'result.html')
     self.response.out.write(template.render(path, template_values))
Beispiel #20
0
#!/usr/bin/python

print 'Content-Type: text/html'
print
print '<html>'
print '<head><title>Hello from Python</title></head>'
print '<body>'
print '<h2>Hello from Python</h2>'
print '</body></html>'

import sessions
session = sessions.Session()
print(session)
Beispiel #21
0
 async def start_session(self, name, user, channel):
     session = sessions.Session(name, user, channel)
     self.sessions[channel] = session
     return