Exemple #1
0
    def on_message(self, data_json):
        '''
        Runs when socket send some message.
        Validating the data, save data and render new message html template

        :param data_json: form from socket in json
        :raise HTTPError: if user is not joined to chat or form data is not valid
        :return: None
        '''
        data = tornado.escape.json_decode(data_json)

        #if not in chat - raise HTTPError
        if not ChatUser.has_access(self.user_id, data['chat_id']):
            raise tornado.web.HTTPError(400)

        form = MessageForm(self._format_data_to_form(data))

        #if bad data - raise HTTPError
        if not form.validate():
            raise tornado.web.HTTPError(400)

        #adding message to DB
        message = Message()
        form.populate_obj(message)
        message.user_id = self.user_id
        db.add(message)
        db.commit()

        current_user = User(name=self.user_name, id=self.user_id)

        data_to_response = {'id': message.id,
                            'message': self.render_to_response("chat/message.html", return_data=True,
                                                   message=message, user=current_user)}

        self.__class__.send_updates(data_to_response)
Exemple #2
0
def logout_user(sid):
    try:
        user = dbi.query(User).filter_by(sid=sid).one()
        user.sid = None
        dbi.commit()
        return responded_ok()
    except sqlalchemy.orm.exc.NoResultFound:
        raise BadUserSid()
Exemple #3
0
  def on_data(self, data):
    tweet = json.loads(data) 

    user = tweet['user']['name']
    text = tweet['text']
    # ignore text that doesn't contain one of the keywords
    matches = re.search(self.regex, tweet['text'].lower()) 	
    if not matches:
        return True

    # ignore retweets
    if re.search(self.retweets_re, tweet['text']): 
        return True

    location = tweet['user']['location']
    source = tweet['source']
    d = dateutil.parser.parse(tweet['created_at'])

    # localize time - you need to use the normalize() method to handle daylight saving time and other timezone transitions
    d_tz = self.utc.normalize(d)  
    #  building a localized time by converting an existing localized time using the standard astimezone() method
    localtime = d.astimezone(self.sgtz) 
    # time.strftime(format[, t]) - Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument. returns a locale dependent byte string.
    tmstr = localtime.strftime("%Y%m%d-%H:%M:%S")  
    splittedString = tmstr.split('-')[1]
    hour = splittedString.split(':')[0]

    # Find geolocation of tweeter
    geo = tweet['geo']  
  
    # is this a geocoded tweet?
    if geo and geo['type'] == 'Point':  
      coords = geo['coordinates']
    
    # print summary of tweet
    print('%s\n%s\n%s\n%s\n%s\n\n ----------------\n' % (user, location, source, tmstr, text))

    tweets = {
      'title': self.terms[0],
      'author': self.terms[1],
      'bookid': self.id,
      'dateposted': tmstr,
      'tweetcontent': text
    }  
    print('tweets ', tweets)
    cursor = cnx.cursor()
    sql = "insert into Tweets (Author,Title,DatePosted,bookid,TweetContent) values (%s, %s, %s, %s, %s)"
    values = (tweets['author'],tweets['title'],tweets['dateposted'], tweets['bookid'], tweets['tweetcontent'])
    cursor.execute(sql, values)
    # print('last ', cursor.lastrowid)
    # result = cursor.lastrowid
    cursor.close()
    cnx.commit() 
  
    return True
Exemple #4
0
    def post(self, form):
        '''Create new Chat object, populate it, save and render new chats list'''
        chat = Chat()
        form.populate_obj(chat)
        chat.user_id = self.user_id
        db.add(chat)
        db.commit()

        #re-render block with chats
        user_in_chats = ChatUser.get_user_chats(self.user_id)
        chats = db.query(Chat).all()
        self.render_to_response("chat/chats_list.html", chats=chats, user_in_chats=user_in_chats)
Exemple #5
0
    def join_switcher(cls, user_id, chat_id):
        '''
        Switch user joining in some chat. If user is already joined - unjoin him, if not - join

        :param user_id: int - id of user to switch
        :param chat_id: int - id of chat to switch in
        :return: None
        '''
        try:
            row = db.query(ChatUser).filter(cls.chat_id==chat_id, cls.user_id==user_id).one()
        except NoResultFound:
            row = cls(user_id=user_id, chat_id=chat_id)
            db.add(row)
        else:
            db.delete(row)

        db.commit()
Exemple #6
0
    def post(self, form):
        #redirect to main if already logined
        if self.user_id:
            self.redirect("/")

        #if have some errors - again render registration form with errors
        if form.errors:
            self.render_to_response("registration.html", form=form)
            return

        #if all are OK - add user
        user = User()
        form.populate_obj(user)
        db.add(user)
        db.commit()

        self.render_to_response("registration_end.html", name=self.get_argument("name"))
Exemple #7
0
    return title, year, episode


def add_to_db(line):
    line = line.split('?!WTF?!')
    m = Movie()
    m.title = line[0]
    m.year = line[1]
    if m.year.isnumeric():
        db.add(m)


# titles = {}
# # for movie in [item.strip() for item in open(file_1).readlines()]:
# #     titles.add(movie)


# for line in [item.strip() for item in open(file_2, encoding='latin-1').readlines()]:
#     data = clean(line)
#     if data:
#         titles[data[0]] = data[1]

# f = open('temp', 'w+')
# for x, y in titles.items():
#     f.write('{}?!WTF?!{}\n'.format(x, y))

f = open('temp')
for i in f.readlines():
    add_to_db(i.strip())
db.commit()
            (
            id VARCHAR(255) NOT NULL,
            name TEXT NOT NULL,
            title TEXT NOT NULL, 
            created INT NOT NULL
            )
            """)

cur.execute("""
            CREATE TABLE main_submissions
            (
            id VARCHAR(255) NOT NULL,
            subreddit_id VARCHAR(255) NOT NULL,
            content TEXT
            )
            """)

cur.execute("""
            CREATE TABLE main_comments
            (
            id VARCHAR(255) NOT NULL,
            subreddit_id VARCHAR(255) NOT NULL,
            submission_id VARCHAR(255) NOT NULL,
            content TEXT
            )
            """)

db.commit()
cur.close()
db.close()