Beispiel #1
0
 def __init__(self, host='localhost', port=8080):
     self.host = host
     self.port = port
     self.base_url = "http://" + host + ":" + str(port)
     self.session = Session()
     self.origin_database_value = self.session.query(Table).\
         filter(Table.id == 1).\
         first().value
Beispiel #2
0
def update(token, methods=['POST']):
    db = sqlite3.connect('db.sqlite')
    session = Session(db, token)
    game = session.load()
    update = request.form.get('action')
    changes = game.update(update)
    session.update(changes)
    return changes  # @TODO : Json formatted
Beispiel #3
0
def get_latest_articles(city):
    session = Session()
    single_data = session.query(Result.timestamp, Result.summary, City.city_name).\
                        join(City, Result.city_id == City.city_id).\
                        filter(City.city_name == city).\
                        order_by(Result.timestamp.desc()).\
                        limit(10).from_self().\
                        order_by(Result.timestamp.asc()).all()

    single_df = pd.DataFrame.from_records(
        single_data, columns=['timestamp', 'summary', 'city'])
    single_df['pos'] = single_df.summary.apply(value_from_json,
                                               path='polarity.positive')
    single_df['neg'] = single_df.summary.apply(value_from_json,
                                               path='polarity.negative')
    single_df['net'] = single_df.summary.apply(value_from_json,
                                               path='polarity.neutral')
    single_df['date'] = single_df.timestamp.apply(
        lambda x: datetime.fromtimestamp(x).strftime('%d.%m.%Y'))

    timeline_graph_data = [
        go.Scatter(
            x=single_df['date'],
            y=single_df[i[0]],
            mode='lines+markers',
            name=polarity_alias[i[0]],
            connectgaps=True,
            line=dict(color=i[1]),
        ) for i in zip(['pos', 'net', 'neg'],
                       [GOOD_COLOR, NEUTRAL_COLOR, BAD_COLOR])
    ]

    timeline_graph_layout = dict(title=city,
                                 yaxis=dict(
                                     title='Количество новостей',
                                     autorange=True,
                                 ),
                                 legend=dict(orientation="h"))

    session.close()
    return dict(data=timeline_graph_data, layout=timeline_graph_layout)
Beispiel #4
0
def get_latest_articles(city):
    session = Session()
    articles = session.query(
        Article.title,
        Article.text,
        Article.timestamp,
        Article.analysis).\
    join(City, Article.city_id == City.city_id).\
    filter(City.city_name == city).\
    order_by(Article.timestamp.desc()).\
    limit(6).all()

    latest_articles = [
        html.Div([
            html.Div([
                html.Div([
                    html.P([
                        datetime.fromtimestamp(
                            a.timestamp).strftime('%d.%m.%Y')
                    ],
                           className='date'),
                ],
                         className='col'),
                html.Div([
                    html.P([json.loads(a.analysis)['polarity']],
                           className='article-polarity')
                ],
                         className='col')
            ],
                     className='row'),
            html.H5([a.title], className='article-title'),
            html.P([a.text], className='article-text'),
            html.Hr(),
        ],
                 className='article-teaser') for a in articles
    ]

    session.close()
    return latest_articles
Beispiel #5
0
    def do_POST(self):
        self.prepare()

        request = Request()
        request.headers = self.headers
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        request.data = post_data.decode('utf-8')
        response = Response()

        if self.path == CONNECT_TEST_PATH:
            response = make_response_test_connection()
            response.data += ' ' + request.data
        else:
            if not self.is_authenticated():
                response = make_response_bad_auth()
            else:
                if not self.path == RPC_PATH:
                    response = make_response_bad_request()
                else:
                    Session.handle_request(request, response)

        response.send(self)
Beispiel #6
0
    def test_init(self):
        print "Concurrency test init..."
        print "Origin database value: {}".format(self.origin_database_value)

        query_thread = threading.Thread(target=self.query)
        update_thread = threading.Thread(target=self.update)
        query_thread.start()
        update_thread.start()

        update_thread.join()
        query_thread.join()

        print "Now Cache value : {}".format(redis_client.get(key))
        print "Now Database value: {}".format(
            Session().query(Table).filter(Table.id == 1).first().value)
Beispiel #7
0
class Client(object):
    def __init__(self, host='localhost', port=8080):
        self.host = host
        self.port = port
        self.base_url = "http://" + host + ":" + str(port)
        self.session = Session()
        self.origin_database_value = self.session.query(Table).\
            filter(Table.id == 1).\
            first().value

    def query(self):
        print "Query thread begin..."
        res = requests.get(self.base_url + "/query")
        print "Query get value : {}".format(res.content)

    def update(self):
        print "Update thread begin..."
        print "Update value {}".format(self.origin_database_value + 1)
        requests.get(self.base_url + "/update/" +
                     str(self.origin_database_value + 1))
        print "Update over"

    def test_init(self):
        print "Concurrency test init..."
        print "Origin database value: {}".format(self.origin_database_value)

        query_thread = threading.Thread(target=self.query)
        update_thread = threading.Thread(target=self.update)
        query_thread.start()
        update_thread.start()

        update_thread.join()
        query_thread.join()

        print "Now Cache value : {}".format(redis_client.get(key))
        print "Now Database value: {}".format(
            Session().query(Table).filter(Table.id == 1).first().value)
Beispiel #8
0
labels = polarity_alias.keys()


sql = """
SELECT timestamp, summary, city_name, coordinates FROM
    (SELECT max(R.timestamp) AS mxts, C.city_id
    FROM cities AS C JOIN results AS R ON C.city_id = R.city_id
    GROUP BY C.city_id) AS t
JOIN
    (SELECT R.timestamp, R.summary, C.city_name, C.coordinates, C.city_id
    FROM cities AS C 
    JOIN results AS R ON C.city_id = R.city_id) AS a
ON t.mxts = a.timestamp AND a.city_id = t.city_id;
""" # thanks to postres

session = Session()
city_data = session.execute(text(sql))

columns = ['timestamp', 'summary', 'city', 'coordinates']
city_df = pd.DataFrame.from_records(city_data, columns=columns)
city_df[['lat', 'lon']] = city_df['coordinates'].str.split(',', expand=True)

city_df['pos'] = city_df.summary.apply(value_from_json,
                                       path='polarity.positive')
city_df['neg'] = city_df.summary.apply(value_from_json,
                                       path='polarity.negative')
city_df['net'] = city_df.summary.apply(value_from_json,
                                       path='polarity.neutral')

city_df['P'] = city_df.pos / (city_df.pos + city_df.neg + city_df.net)
city_df['desc'] = city_df.city + '<br>' + \
Beispiel #9
0
    module = Module(module_id=mod_id,
                    course_id=course_id,
                    name=name,
                    order=ord)
    db.session.add(module)
    db.session.commit()

cur.execute('select * from on_demand_sessions where course_id = %s',
            (course_id, ))
for (course_id, session_id, start, end, _, branch_id) in cur.fetchall():
    if db.session.query(Session).filter(Session.start_date == start).count():
        s = Session.query.filter(Session.start_date == start).order_by(
            Session.version.desc()).first()
        session = Session(session_id=session_id,
                          course_id=course_id,
                          start_date=start,
                          end_date=end,
                          version=s.version + 1,
                          course_branch_id=branch_id)
    else:
        session = Session(session_id=session_id,
                          course_id=course_id,
                          start_date=start,
                          end_date=end,
                          version=1,
                          course_branch_id=branch_id)

    db.session.add(session)
    db.session.commit()

session = Session.query.filter(
    Session.session_id == 'mGhKAXoWEee1jApzGcQi8A')[0]
Beispiel #10
0
    def substract_balance(unique_number, substract_value) -> Dict:
        session = Session()
        try:
            session.connection(
                execution_options={'isolation_level': 'READ COMMITTED'})
            user = session.query(User).filter_by(
                unique_number=unique_number).with_for_update().one()
            if user is None:
                raise UserNotFoundException(
                    "Not found user with unique number: {}".format(
                        unique_number))
            if not user.status:
                raise UserIsBlockedException("User is blocked")

            if user.balance - user.holds - substract_value >= 0:
                user.holds += substract_value
                session.commit()
                user_info = user.serialize()
            else:
                raise NotEnoughMoneyException("Not enough money")
        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()

        return user_info
Beispiel #11
0
    def increase_balance(unique_number, increase_value) -> Dict:
        session = Session()
        try:
            session.connection(
                execution_options={'isolation_level': 'READ COMMITTED'})
            user = session.query(User).filter_by(
                unique_number=unique_number).with_for_update().one()
            if user is None:
                raise UserNotFoundException("User not found")
            if not user.status:
                raise UserIsBlockedException("User is blocked")
            user.balance += increase_value

            session.commit()
            user_info = user.serialize()
        except SQLAlchemyError:
            session.rollback()
            raise
        finally:
            session.close()

        return user_info
Beispiel #12
0
def tick(token, time):
    db = sqlite3.connect('db.sqlite')
    session = Session(db, token)
    game = session.load()
    changes = game.tick(int(time))
    return changes
Beispiel #13
0
def main(token):
    db = sqlite3.connect('db.sqlite')
    session = Session(db, token)
    game = session.load()
    return render_template('assets/html/game.html')
Beispiel #14
0
def new():
    db = sqlite3.connect('db.sqlite')
    session = Session(db)
    id = session.create()
    return redirect(url_for('session', session=id))