def movie_add(): form = MovieForm() if form.validate_on_submit(): data = form.data file_url = secure_filename(form.url.data.filename) file_logo = secure_filename(form.logo.data.filename) if not os.path.exists(app.config["UP_DIR"]): # 如果没有 "UP_DIR" 目录,就新建一个 os.makedirs(app.config["UP_DIR"]) # 授权文件夹可读写 os.chmod(app.config["UP_DIR"], "rw") url = change_filename(file_url) logo = change_filename(file_logo) # 保存 form.url.data.save(app.config["UP_DIR"] + url) form.logo.data.save(app.config["UP_DIR"] + logo) movie = Movie(title=data["title"], url=url, info=data["info"], logo=logo, star=int(data["star"]), playnum=0, commentnum=0, tag_id=int(data["tag_id"]), area=data["area"], release_time=data["release_time"], length=data["length"]) db.session.add(movie) db.session.commit() flash("添加电影成功!", "ok") return redirect(url_for('admin.movie_add')) return render_template("admin/movie_add.html", form=form)
def update_films(url, base): """ update_films add missing films, people and their connections in the database. Parameters: url (str) -- API Base URL """ cast = get_cast(url) # Gathering information about new films for film in base: r = Movie(film['id'], film['title'], int(film['release_date'])) db.session.add(r) for member_id in cast["films"][film['id']]: name = cast["people"][member_id] # Update our Character list if Character.query.filter_by(id=member_id).first() is None: m = Character(member_id, name) db.session.add(m) c = Cast(r.id, member_id) db.session.add(c) db.session.commit()
def get_movies(): start, count = paginate() q = request.args.get('q', None) movies = Movie.get_paginate_models_with_img(start, count, q, err_msg='相关电影不存在') return jsonify(movies)
def render_edit_movie(id): movie = Movie.get(id=id, ignore=404) if request.method == 'POST': movie.title = request.form['title'] movie.summary = request.form['summary'] movie.save() return redirect(url_for('movies.render_movie', id=movie.meta.id)) return render_template('movies/detail.html', movie=movie, is_edit=True)
def add_movie(payload): try: body = request.get_json() similar_movie_flag = Movie.query.filter( Movie.title == body.get('title')).one_or_none() if similar_movie_flag is not None: return jsonify({ 'message': 'Similar Movie Title Already Exist in Database.' }), 422 new_movie = Movie( title=body.get('title'), desc=body.get('desc'), release_date=body.get('release_date') ) new_movie.save() return jsonify({ 'movie': new_movie.to_json(), 'success': True }), 201 except Exception: abort(500)
def make_movie(): rank = 1 title = 'Guardians of the Galaxy' genres = [Genre('Action'), Genre('Adventure'), Genre('Sci-Fi')] description = 'A group of intergalactic criminals are forced to work together to stop a fanatical warrior from taking control of the universe.' directors = [Director('James Gunn')] actors = [Actor('Chris Pratt'), Actor('Vin Diesel'), Actor('Bradley Cooper'), Actor('Zoe Saldana')] year = 2014 runtime = 121 rating = 8.1 votes = 757074 revenue = 333.13 metascore = 76 return Movie(rank, title, genres, description, directors, actors, year, runtime, rating, votes, revenue, metascore)
def movie(genre, director, actor): rank = 1 title = 'Guardians of the Galaxy' genres = [genre] description = 'A group of intergalactic criminals are forced to work together to stop a fanatical warrior from taking control of the universe.' directors = [director] actors = [actor] year = 2014 runtime = 121 rating = 8.1 votes = 757074 revenue = 333.13 metascore = 76 return Movie(rank, title, genres, description, directors, actors, year, runtime, rating, votes, revenue, metascore)
def movie_add(): # 将file跟form表单内容整合 values = CombinedMultiDict([request.files, request.form]) # id_dict=MultiDict([('id',10)]) # values=CombinedMultiDict([id_dict,values]) form = MovieAddForm(values) tags = Tag.query.all() if request.method == 'POST' and form.validate(): upload = Upload_file() file_url = upload.video(form.url.data) file_logo = upload.image(form.logo.data) values = form.data values['url'] = file_url values['logo'] = file_logo values['playnum'] = 0 values['commentnum'] = 0 with db.auto_commit(): movie = Movie() movie.set_attr(values) db.session.add(movie) Oplog('添加电影:' + movie.title) flash('电影添加成功~', 'ok') return redirect(url_for('admin.movie_add')) return render_template('admin/movie_add.html', tags=tags, form=form)
def render_homepage(): is_search = False search = Movie.search() query = request.args.get('search', None) genre = request.args.get('genre', []) min_rate = request.args.get('min-rate', '') max_rate = request.args.get('max-rate', '') if request.args: is_search = True q = Q('bool', must=[Q('match', title=query)], should=[Q('match', summary=query)]) search = search.query("match", q) print(query, genre, min_rate, max_rate) search = search.filter('terms', genre=genre) results = search.execute() all_genre = get_all_genre() return render_template('homepage/home.html', movies=results, genres=all_genre, is_search=is_search)
def post(self): parser = reqparse.RequestParser() parser.add_argument('title', type=str, required=True), parser.add_argument('genre_id', type=int, required=True), parser.add_argument('cast_id', action='append', type=str) parsed_args = parser.parse_args() title = parsed_args['title'] genre_id = parsed_args['genre_id'] existing_movie = Movie.query.filter(Movie.title == title).first() if existing_movie: return abort( 400, 'Movie with title: {} already exists in database.'.format( parsed_args['title'])) movie = Movie(title=title, genre_id=genre_id) if self.args['cast_id']: for id in self.args['cast_id']: actor = Actor.query.filter(Actor.id == id).first() if not actor: return abort( 404, 'Actor with id: {} does not exist in database.'.format( id)) movie.cast.append(actor) db.session.commit() try: db.session.add(movie) db.session.commit() except: return abort( 500, 'An error occurred while trying to add new movie to database.') return jsonify(message='New movie has been created.')
def add(): form = MovieForm() log('进入添加电影路由') if form.validate_on_submit(): data = form.data log('输入不为空') movie_count = Movie.query.filter_by(title=data['title']).count() if movie_count == 1: flash("片名已经存在!", "err") return redirect(url_for(".add", form=form)) path = app.config['UP_DIR'] log('data', data) log('form.logo', form.logo) log('form.logo.data', form.logo.data) log('form.logo.data.filename', form.logo.data.filename) url = saved_file(path, form.url.data) logo = saved_file(path, form.logo.data) movie = Movie(data) movie.url = url movie.logo = logo movie.save() flash('添加电影成功!', 'ok') return redirect(url_for('.add')) return render_template('admin/movie/add.html', form=form)
def get_movie_from_id(movie_id): movie = Movie.objects(id=movie_id).first() return movie.to_json(), 200
'year': 2014 } app = Flask(__name__, instance_relative_config=False) app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL app.config[ 'SQLALCHEMY_TRACK_MODIFICATIONS'] = False # silence the deprecation warning db.init_app(app) with app.app_context(): db.create_all() actor = Actor.create(**data_actor) print('created actor:', actor.__dict__, '\\n') movie = Movie.create(**data_movie) print('created movie:', movie.__dict__, '\\n') upd_actor = Actor.update(1, **data_actor_upd) print('updated actor:', upd_actor.__dict__, '\\n') upd_movie = Movie.update(1, **data_movie_upd) print('updated movie:', upd_movie.__dict__, '\\n') add_rels_actor = Actor.add_relation(1, upd_movie) movie_2 = Movie.create(**data_movie) add_more_rels_actor = Actor.add_relation(1, movie_2) print('relations list:', add_more_rels_actor.filmography, '\\n') clear_rels_actor = Actor.clear_relations(1) print('all relations cleared:', clear_rels_actor.filmography, '\\n')
def delete_movie(id): Movie.remove_model(id, err_msg='相关电影不存在') return Success(msg='电影删除成功')
def scrape_cmd(genre, page_number): movies = batch_scraping_by_genre(genre, page_number or 1) for res_scraping in movies: new_movie = Movie(title=res_scraping["title"]) new_movie.rating = res_scraping["rating"] new_movie.reviews = res_scraping["review"] new_movie.summary = res_scraping["summary"] new_movie.writers = res_scraping["writers"] new_movie.directors = res_scraping["directors"] new_movie.genre = res_scraping["genre"] new_movie.stars = res_scraping["stars"] new_movie.year = res_scraping["year"] new_movie.casts = res_scraping["cast"] new_movie.img = res_scraping["img"] new_movie.meta.id = res_scraping["id"] new_movie.save() print(new_movie)
def create_movie(): form = CreateOrUpdateMovieForm().validate_for_api() Movie.new_model(form.data, err_msg='相关电影已存在') return Success('电影创建成功')
def update_movie(id): form = CreateOrUpdateMovieForm().validate_for_api() Movie.edit_model(id, form.data, err_msg='相关电影不存在') return Success(msg='电影更新成功')
def render_movie(id): movie = Movie.get(id=id, ignore=404) return render_template('movies/detail.html', movie=movie)
def post_movie(): movie = Movie() movie.runtime = request.json.get('runtime') movie.director = request.json.get('director') movie.country = request.json.get('country') movie.genre = request.json.get('genre') movie.launch_date = request.json.get('launch_date') movie.movie_title = request.json.get('movie_title') movie.save() return movie.to_json(), 200
def render_add_movies(): if request.method == 'GET': return render_template('movies/add.html') elif request.method == 'POST': movies_url = request.form['moviesUrl'] movies_id = movies_url.split('/')[4] movie_data = Movie.get(id=movies_id, ignore=404) print('movie data', movie_data) if movie_data is None: print('id not found, start scraping') res_scraping = single_scraping(movies_url) new_movie = Movie(title=res_scraping["title"]) new_movie.rating = res_scraping["rating"] new_movie.reviews = res_scraping["review"] new_movie.summary = res_scraping["summary"] new_movie.writers = res_scraping["writers"] new_movie.directors = res_scraping["directors"] new_movie.genre = res_scraping["genre"] new_movie.stars = res_scraping["stars"] new_movie.year = res_scraping["year"] new_movie.casts = res_scraping["cast"] new_movie.img = res_scraping["img"] new_movie.meta.id = movies_id new_movie.save() es = Elasticsearch() res = es.get(index='moovie', doc_type='_doc', id=movies_id) return jsonify(res['_source'])
from elasticsearch_dsl import A from app.models.movie import Movie from pprint import pprint search = Movie.search() def get_all_genre(): genre_agg = A('terms', field='genre.raw') search.aggs.bucket('genre_terms', genre_agg) result = search.execute() # pprint(result.aggregations['genre_terms']['buckets']) return result.aggregations['genre_terms']['buckets']
def setUp(self): ''' Set up method that will run before every Test ''' self.new_movie = Movie(1234,'Python Must Be Crazy','A thrilling new Python Series','/khsjha27hbs',8.5,129993)
def update_movie(movie_id): movie = Movie.objects(id=movie_id).first() movie.update(**request.json) movie.reload() return movie.to_json(), 200
def delete_movie(movie_id): movie = Movie.objects(id=movie_id).first() movie.delete() return '', 204
def populate(db): """Populates database with admin and initial theater data""" from flask import current_app from app.models.user import User from app.models.role import Role # Create admin admin_role = Role(name='superuser') db.session.add(admin_role) try: db.session.commit() except Exception as e: print("admin role already exists") admin_user = User( username=current_app.config["ADMIN_USERNAME"], email=current_app.config["ADMIN_EMAIL"], password=current_app.config["ADMIN_PASSWORD"], roles=[admin_role,], active=True ) db.session.add(admin_user) try: db.session.commit() except Exception as e: print("admin user already exists") # Create theater models import datetime from app.models.genre import Genre from app.models.actor import Actor from app.models.director import Director from app.models.movie import Movie from app.models.auditorium import Auditorium from app.models.seat import Seat from app.models.show import Show # Genres action = Genre(name="Action") comedy = Genre(name="Comedy") drama = Genre(name="Drama") db.session.add_all([ action, comedy, drama ]) # Actors ridley = Actor(name="Daisey Ridley") driver = Actor(name="Adam Driver") cooper = Actor(name="Bradley Cooper") lawrence = Actor(name="Jennifer Lawrence") eisenberg = Actor(name="Jesse Eisenberg") garfield = Actor(name="Andrew Garfield") db.session.add_all([ ridley, driver, cooper, lawrence, eisenberg, garfield, ]) # Directors johnson = Director(name="Rian Johnson") russel = Director(name="David O. Russel") fincher = Director(name="David Fincher") db.session.add_all([ johnson, russel, fincher, ]) # Movies last_jedi = Movie( title="The Last Jedi", genre=action, actors=[ridley, driver], director=johnson, description="The Last Jedi follows Rey as she seeks the aid of Luke Skywalker, " "in hopes of turning the tide for the Resistance in the fight " "against Kylo Ren and the First Order, while General Leia Organa, " "Finn, and Poe Dameron attempt to escape a First Order attack on " "the dwindling Resistance fleet.", rating="PG13", runtime=datetime.time(2, 30) ) silver_lining = Movie( title="Silver Linings Playbook", genre=comedy, actors=[cooper, lawrence], director=russel, description="After losing his job and wife, and spending time in a mental institution, " "Pat Solatano (Bradley Cooper) winds up living with his parents " "(Robert De Niro, Jacki Weaver). He wants to rebuild his life and reunite with " "his wife, but his parents would be happy if he just shared their obsession " "with the Philadelphia Eagles. Things get complicated when Pat meets Tiffany " "(Jennifer Lawrence), who offers to help him reconnect with his wife, " "if he will do something very important for her in exchange.", rating="PG13", runtime=datetime.time(2, 2) ) social_network = Movie( title="The Social Network", genre=drama, actors=[eisenberg, garfield], director=fincher, description="In 2003, Harvard undergrad and computer genius Mark Zuckerberg (Jesse Eisenberg) " "begins work on a new concept that eventually turns into the global social network " "known as Facebook.", rating="PG13", runtime=datetime.time(2, 1) ) db.session.add_all([ last_jedi, silver_lining, social_network ]) # Auditorium screen1 = Auditorium(name="Screen 1") screen2 = Auditorium(name="Screen 2") screen3 = Auditorium(name="Screen 3") db.session.add_all([ screen1, screen2, screen3 ]) ######### # Seating ######### # screen1 for row in ('A', 'B', 'C', 'D', 'E',): for i in range(1,13): #seat number db.session.add( Seat( number=row + str(i), row=row, auditorium=screen1, is_empty_space= True if i == 7 else False ) ) for i in range(1,13): # empty row db.session.add( Seat( number='F' + str(i), row=row, auditorium=screen1, is_empty_space= True ) ) for row in ('G', 'H'): for i in range(1,13): db.session.add( Seat( number=row + str(i), row=row, auditorium=screen1, is_empty_space= False ) ) # screen2 for row in ('A', 'B', 'C', 'D', 'E'): for i in range(1,15): #seat number db.session.add( Seat( number=row + str(i), row=row, auditorium=screen2, is_empty_space=False ) ) for i in range(1,15): # empty row db.session.add( Seat( number='F' + str(i), row='F', auditorium=screen2, is_empty_space = True ) ) for i in range(1,15): db.session.add( Seat( number='G' + str(i), row='G', auditorium=screen2, is_empty_space = True if i == 1 or i == 2 or i == 13 or i == 14 else False ) ) for i in range(1,15): db.session.add( Seat( number='H' + str(i), row='H', auditorium=screen2, is_empty_space = True if i == 1 or i == 13 else False ) ) # screen3 for row in ('A', 'B', 'C', 'D', 'E'): for i in range(1,10): #seat number db.session.add( Seat( number=row + str(i), row=row, auditorium=screen3, is_empty_space= True if i == 5 else False ) ) # Shows # last jedi - screen1 for movie in (last_jedi,): showdate = datetime.date.today() for i in range(7): # next 7 days for showtime in ((10, 0), (13, 30), (17, 15), (21, 45)): db.session.add( Show( time=datetime.time(*showtime), date=showdate, movie=movie, auditorium=screen1, ) ) showdate = showdate + datetime.timedelta(hours=24) # silver lining - screen2 for movie in (silver_lining,): showdate = datetime.date.today() for i in range(7): # next 7 days for showtime in ((9, 0), (12, 15), (16, 0), (22, 30)): db.session.add( Show( time=datetime.time(*showtime), date=showdate, movie=movie, auditorium=screen2, ) ) showdate = showdate + datetime.timedelta(hours=24) # social network - screen3 for movie in (social_network,): showdate = datetime.date.today() for i in range(7): # next 7 days for showtime in ((9, 30), (11, 45), (14, 0), (19, 45)): db.session.add( Show( time=datetime.time(*showtime), date=showdate, movie=movie, auditorium=screen3, ) ) showdate = showdate + datetime.timedelta(hours=24) try: db.session.commit() except Exception as e: print(f"Models may already exist: {e}")
def get_movie(id): movie = Movie.get_model_with_img(id, err_msg='相关电影不存在') return jsonify(movie)
def import_data_from_csv(file_path): """ Import data from a csv file into database :return: """ try: with open(file_path) as csv_file: reader = csv.reader(csv_file, delimiter=',') # Init dictionaries movies, actors, writers, directors, locations = import_data_from_database() # FIXME : test header ! header = next(reader) if header[0] != 'Title' or header[1] != 'Release Year': return "Bad File.." for row in reader: # Read CSV line name = row[0].strip() location = row[2] fun_facts = row[3] # Movie already exists create new location if name in movies: if '' != location: new_location = Location(location, fun_facts, movies[name]) db.session.add(new_location) continue # Read more information from csv line about movie release_year = row[1] production = row[4] distributor = row[5] director = row[6] writer = row[7] movie_actors = [row[8], row[9], row[10]] # Create a new Movie movie = Movie(name, release_year, production, distributor) # Add director if '' != director: if director not in directors: director = Director(director) db.session.add(director) db.session.flush() # Save director id in local dictionary directors[director.name] = director.id # add director_id to movie movie.add_director(director.id) else: movie.add_director(directors[director]) # Add writer if '' != writer: if writer not in writers: writer = Writer(writer) db.session.add(writer) db.session.flush() # Save director information writers[writer.name] = writer.id # add director_id to movie movie.add_writer(writer.id) else: movie.add_writer(writers[writer]) # Add Actors for actor_name in movie_actors: if actor_name != '': if actor_name not in actors: actor = Actor(actor_name) db.session.add(actor) db.session.flush() # Save director information actors[actor_name] = actor.id # add actor to movie movie.add_actor(actor) else: movie.add_actor(actor_name) # Add Movie in DB db.session.add(movie) db.session.flush() # Store movie id in local dictionary movies[name] = movie.id # Create new Location, if not empty and does not exist if '' != location: if (location, movie.id) not in locations: new_location = Location(location, fun_facts, movie.id) db.session.add(new_location) db.session.flush() locations[(location, movie.id)] = new_location.id # Commit imported data db.session.commit() except FileNotFoundError: print("File : `" + file_path + '` not found')
def get_movie(): movies = Movie.objects().all() return jsonify(movies), 200