Ejemplo n.º 1
0
def load_series():
    """Loads sample series into database"""
    print("Loading series")

    db.session.add(Series(series_name="Mistborn", goodreads_id="40910"))
    db.session.add(Series(series_name="Harry Potter", goodreads_id="45175"))
    db.session.add(Series(series_name="The Giver", goodreads_id="43606"))

    db.session.commit()
Ejemplo n.º 2
0
 def json(self):
     # Prefix the UUID from the client with k as it may start with a number
     name = self.require("name")
     id = self.request.get("id")
     if id:
         series = Series(name=name, key_name="k" + id)
     else:
         series = Series(name=name)
     series.put()
     for value in json.loads(self.request.get('values', '[]')):
         time = datetime.fromtimestamp(self.extract("time", value)/1000.0)
         createValue(self.extract("value", value), series, time, value.get("id", None))
     return {"series": series.jsonify()}
Ejemplo n.º 3
0
    def create_series(self, name, desc, team_id, tags=None, series_id=None):
        """
        Adds a new series to the database

        :type name: str
        :param name: Name of the Series

        :type desc: str
        :param desc: Description of the Series

        :type team_id: str
        :param team_id: Team Id to which this Series belongs to

        :type tags: str
        :param tags: Tags for a Series

        :type series_id: str
        :param series_id: ID of the Series
        """

        if not series_id:
            series_id = convert_name_to_id(name)

        if not self.series_exists(series_id):
            new_series = Series(id=series_id,
                                name=name,
                                description=desc,
                                tags=tags,
                                team_id=team_id)

            self.session.add(new_series)
            self.session.flush()
        return series_id
Ejemplo n.º 4
0
def show_series_results():
    """ Returns last book of series """
    series_id = request.form.get("id")
    series_name = request.form.get("name")

    date = request.form.get("date")
    date_str = " ".join(date.split()[1:])
    py_date = datetime.strptime(date_str, "%b %d %Y")

    timeframe = int(request.form.get("timeframe"))
    tf_str = timeframes[timeframe]
    td = timedelta(days=timeframe)

    if series_id and series_name:  # if there is a series id and name
        results = get_last_book_of_series(series_name, series_id, py_date, td)

        if "search_history" in session:
            search = (date, tf_str, series_name, results["results"])
            # this looks redundant, but if I try to modify the session value directly
            # it doesn't update, so it has to be like this
            s_history = session["search_history"]
            s_history.append(search)
            session["search_history"] = s_history

        if not Series.query.filter_by(goodreads_id=series_id).first(
        ):  # if series is not in database
            db.session.add(
                Series(goodreads_id=series_id, series_name=series_name))
            db.session.commit()

        return jsonify(results)

    else:
        return jsonify({"status": "error"})
Ejemplo n.º 5
0
def insert():
    try:
        series = Series.from_dict(flask.request.get_json())
    except (ValueError, KeyError):
        return "ERROR Invalid Series object"
    with flask.current_app.ydb.session as session:
        SeriesRepository(session).insert(series)
    return "OK"
Ejemplo n.º 6
0
 def get(self):
     if not self.request.get("debugjs"):
         libs = ["all.min.js"]
     else:
         libs = jslibs
     series = json.dumps([series.jsonify() for series in Series.all()])
     self.response.out.write(template.render("%s/index.html" % template_dir, {"jslibs":libs,
         "series":series}))
Ejemplo n.º 7
0
def display_index():
    """Display index template."""

    characters = Character.all()
    series = Series.all()

    return render_template("index.html",
                            characters=characters,
                            series=series)
Ejemplo n.º 8
0
def create_series(code, name):
    """Create and return a new series."""

    series = Series(series_code=code, name=name)

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

    return series
Ejemplo n.º 9
0
def generate_random():
    start_id = flask.request.args.get("startId", type=int)
    count = flask.request.args.get("count", type=int)
    with flask.current_app.ydb.session as session:
        series_repository = SeriesRepository(session)
        for series_id in xrange(start_id, start_id + count):
            series_repository.insert(Series(
                series_id=series_id,
                title="Name " + str(series_id),
                series_info="Info " + str(series_id),
                release_date=datetime.datetime.now().date(),
                views=random.randint(0, 1000000)
            ))
    return "OK"
Ejemplo n.º 10
0
def load_series():

    for line in open("csv/series.csv"):
        line = line[:-1]
        name, synopsis, date, chron_order, image = line.split(',')

        series = Series(name=name,
                        synopsis=synopsis,
                        date=date,
                        chron_order=chron_order,
                        image=image)

        db.session.add(series)

    db.session.commit()
Ejemplo n.º 11
0
 def json(self):
     return {"series": [series.jsonify() for series in Series.all()]}
Ejemplo n.º 12
0
 def json(self):
     Series.get(Key(self.require("key"))).delete()
     return {}
Ejemplo n.º 13
0
 def json(self):
     series = Series.get(Key(self.require('seriesKey')))
     return {"value":
             createValue(float(self.require("value")), series, datetime.utcnow()).jsonify()}
Ejemplo n.º 14
0
def get_serie(series_name):
    '''
    - URL da rota: http://localhost:5000/series/<series_name>

    - Rota que faz uma requisição GET na URL series_OMDBapi, para retornar o JSON
    com as informações da série especificada pelo nome (series_name). 
    
    - Caso a série já esteja cadastrada no banco, os dados do JSON são montados 
    à partir das informações da tabela TSeries.

    - Caso a série não esteja cadastrada no banco, os dados do JSON são montados à 
    partir do JSON da API series_OMDBapi.

    Os dados contidos no JSON/TSeries são:

    - 'Title': nome/titulo da série.
    - 'Released': data de estreia do episódio piloto da série.
    - 'Seasons': quantidade de temporadas.
    - 'Runtime': tempo de cada episódio.
    - 'Genre': genêro(s) da série.
    - 'Director': diretor da série (geralmente sendo N/A).
    - 'Writer': escritor(a) da série.
    - 'Actors': atores/atrizes da série.
    - 'Plot': trama/enrredo da série.
    - 'Language': idiomas da série.
    - 'Country': país/paises da série.
    - 'Poster': URL do poster da série.
    '''
    request = requests.get(f'{series_OMDBapi}{series_name}')
    request_json = request.json()
    if "Error" in request_json:
        return jsonify(request_json)
    series = series_dao.get_series_name(series_name)
    if series == None:
        new_series = Series(series_name=request_json['Title'], 
                            series_realese=request_json['Released'],
                            series_seasons=request_json['totalSeasons'],
                            series_episode_runtime=request_json['Runtime'],
                            series_genre=request_json['Genre'],
                            series_director=request_json['Director'],
                            series_writer=request_json['Writer'],
                            series_actors=request_json['Actors'],
                            series_plot=request_json['Plot'],
                            series_language=request_json['Language'],
                            series_country=request_json['Country'],
                            series_poster=request_json['Poster'])
        save_series = series_dao.register_series(new_series)
        series = {
                    "Title": request_json['Title'],
                    "Released": request_json['Released'],
                    "Seasons": request_json['totalSeasons'],
                    "Runtime": request_json['Runtime'],
                    "Genre": request_json['Genre'],
                    "Director": request_json['Director'],
                    "Writer": request_json['Writer'],
                    "Actors": request_json['Actors'],
                    "Plot": request_json['Plot'],
                    "Language": request_json['Language'],
                    "Country": request_json['Country'],
                    "Poster": request_json['Poster']
                }
        return jsonify(series)
    else:
        series = series_dao.get_series_data(series_name)
        for series_data in series:
            series = {
                    "Title": series_data.series_name,
                    "Released": series_data.series_realese,
                    "Seasons": series_data.series_seasons,
                    "Runtime": series_data.series_episode_runtime,
                    "Genre": series_data.series_genre,
                    "Director": series_data.series_director,
                    "Writer": series_data.series_writer,
                    "Actors": series_data.series_actors,
                    "Plot": series_data.series_plot,
                    "Language": series_data.series_language,
                    "Country": series_data.series_country,
                    "Poster": series_data.series_poster
                }
        return jsonify(series)