当前位置: 首页>>代码示例>>Python>>正文


Python Movie.save方法代码示例

本文整理汇总了Python中models.Movie.save方法的典型用法代码示例。如果您正苦于以下问题:Python Movie.save方法的具体用法?Python Movie.save怎么用?Python Movie.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在models.Movie的用法示例。


在下文中一共展示了Movie.save方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_movie

# 需要导入模块: from models import Movie [as 别名]
# 或者: from models.Movie import save [as 别名]
def get_movie(request, pk):
    """
    function to handle request for a particular movie
    GET => uesd to query
    POST w/o id, to insert and return inserted value
    POST w/ id, to update existing record
    :param request: incomming http request
    :param pk: primary key of the movie requested
    :return:
    """
    #check the incomming method
    try:
        if request.method == "GET":
            if pk != '':
                _movie = Movie.objects.get(pk=pk).json()
                response = HttpResponse(_movie, content_type="application/json")
                return response
            else:
                response = search_movie(request)
                return response
                raise Movie.MultipleObjectsReturned()
        elif request.method == 'POST':
            #check if user is authenticated to touch it
            #if pk='', insert, else overwrite
            if pk == '' and has_perm(request, 'IMDB.create_movie'):
                _m = Movie()
            elif pk != '' and has_perm(request, 'IMDB.change_movie'):
                _m = get_object_or_404(Movie, pk=pk)
            else:
                raise PermissionDenied()
            _m.add_using_json(request.body)
            _m.save()
            return HttpResponse(_m.json(), content_type="application/json", status=201)
        elif request.method == 'DELETE':
            if pk != '':
                if has_perm(request, 'delete_movie'):
                    _m = get_object_or_404(Movie, pk=pk)
                    _m.delete()
                    return HttpResponse('delete successful', content_type="application/json", status=200)
                else:
                    raise PermissionDenied()
            else:
                raise Movie.MultipleObjectsReturned()
        else:
            raise Movie.MultipleObjectsReturned()  #avoiding modification to the entire series
    except IntegrityError as ie:
        return HttpResponseBadRequest("{'status':400,'message':'Bad Request -- Integrity violation:" + ie.message + "'}",
                                        content_type="application/json")
    except KeyError as k:
        return HttpResponseBadRequest("{'status':400,'message':'Bad Request -- Key violation:" + k.message + "'}",
                                      content_type="application/json")
    except Movie.MultipleObjectsReturned as e:
        return HttpResponseNotFound(json.dumps({'status': 404, 'message': 'movie not found'}),
                                    content_type="application/json")
    except (Movie.DoesNotExist, Http404):
        return HttpResponseNotFound(json.dumps({'status': 404, 'message': 'movie not found'}),
                                    content_type="application/json")
    except PermissionDenied as p:
        return HttpResponseForbidden(json.dumps({'status': 403, 'message': 'Permission Denied{0:s}'.format(p.message)}),
                                     content_type="application/json")
开发者ID:jiteshpunjabi,项目名称:movie-rest-api,代码行数:62,代码来源:views.py

示例2: saveMovie

# 需要导入模块: from models import Movie [as 别名]
# 或者: from models.Movie import save [as 别名]
def saveMovie (request):
    channel=Channel.objects.get(id=1)
    html = urllib.urlopen('http://sh.meituan.com/dianying').read()
    soup = BeautifulSoup(html)
    for movie in soup.find_all('ul', class_='reco-slides__slides')[0].find_all('li')[0].find_all('a',class_='btn'):
        name = movie['title']
        href = movie['href']
        code = href[href.rfind('/') + 1:href.find('#')]
        m = Movie(name=name,code=code,channel=channel)
        m.save()
    return HttpResponse("save success! ")
开发者ID:unluckyBear,项目名称:django,代码行数:13,代码来源:views.py

示例3: getDetails

# 需要导入模块: from models import Movie [as 别名]
# 或者: from models.Movie import save [as 别名]
def getDetails(identifiers):
	try:
		movie=Movie.objects.get(sourceID=identifiers.sourceID,source=identifiers.source)
	except:
		movie=Movie()
		if identifiers.source=='rottenTomatoes':
			movie=fetchDetailsRottenTomatoes(identifiers)
		elif identifiers.source=='theMovieDB':
			movie=fetchDetailsTheMovieDB(identifiers)
		movie.save()
	return movie	
开发者ID:ebarakos,项目名称:movie-aggregator,代码行数:13,代码来源:utils.py

示例4: callback_post

# 需要导入模块: from models import Movie [as 别名]
# 或者: from models.Movie import save [as 别名]
def callback_post():
    LOGGER.info('Logging Request: METHOD: ' + request.method + ' => ROUTE: /api/movies')
    response.set_header('Date', DATETIMESTAMP)

    try:
        accept = request.headers.get('Accept')
        response.set_header('Content-Type', determine_response_content_type(accept))

        if 'application/json' not in request.headers.get(
                'Content-Type') and 'application/vnd.collection+json' not in request.headers.get('Content-Type'):
            LOGGER.error('Unsupported media type sent')
            response.status = 415
            response_body = ErrorCJ(ROOT, 'Invalid Content-Type', 415,
                                    'application/json and application/vnd.collection+json supported')
            return response_body.to_json()

        request_json = json_loads(request._get_body_string())
        if not request_json:
            raise Exception

        # debug
        # print request_json

        # connect to mongodb
        mongoengine.connect('api')

        movie_dict = dict()
        for item in request_json["template"]["data"]:
            movie_dict[item["name"]] = item["value"]

        # new movie
        movie = Movie()
        movie.sysid = str(uuid.uuid4()).replace("-", "")
        movie.created_on = datetime.datetime.now
        movie.updated_on = datetime.datetime.now
        movie.decode(movie_dict)
        movie.save()

        # send the response
        response.set_header('Location', ROOT + 'movies/' + movie.sysid)
        response.status = 201
        movie = None
        return

    except Exception as e:
        LOGGER.error('Unexpected exception ' + str(e))
        response.status = 500
        response_body = ErrorCJ(ROOT, 'Error Title', 500, str(e))
        return response_body.to_json()
开发者ID:bryanbarnard,项目名称:ISWQ2014,代码行数:51,代码来源:app.py

示例5: test_serialize_unicode

# 需要导入模块: from models import Movie [as 别名]
# 或者: from models.Movie import save [as 别名]
    def test_serialize_unicode(self):
        """Tests that unicode makes the roundtrip intact"""
        actor_name = u"Za\u017c\u00f3\u0142\u0107"
        movie_title = u'G\u0119\u015bl\u0105 ja\u017a\u0144'
        ac = Actor(name=actor_name)
        mv = Movie(title=movie_title, actor=ac)
        ac.save()
        mv.save()

        serial_str = serializers.serialize(self.serializer_name, [mv])
        self.assertEqual(self._get_field_values(serial_str, "title")[0], movie_title)
        self.assertEqual(self._get_field_values(serial_str, "actor")[0], actor_name)

        obj_list = list(serializers.deserialize(self.serializer_name, serial_str))
        mv_obj = obj_list[0].object
        self.assertEqual(mv_obj.title, movie_title)
开发者ID:Terhands,项目名称:django,代码行数:18,代码来源:tests.py

示例6: load_sample_data

# 需要导入模块: from models import Movie [as 别名]
# 或者: from models.Movie import save [as 别名]
def load_sample_data():
    file_path = os.path.abspath('/home/jiteshvp/Dev/ShopSense/InterviewExercise/data/imdb.json')
    with open(file_path, 'r') as f:
        _decoded_json = json.load(f)
        for _json_movie in _decoded_json:
            _movie = Movie(
                popularity=unicode_lower_strip(_json_movie['99popularity']),
                director=unicode_lower_strip(_json_movie['director']),
                movie_name=unicode_lower_strip(_json_movie['name'])
            )
            try:
                _movie.save()
                for _json_genre in _json_movie['genre']:
                    (_genre, _was_created) = Genre.objects.get_or_create(genre_label=unicode_lower_strip(_json_genre))
                    _movie.genre.add(_genre)
                _movie.save()
            except Exception as e:
                pass
开发者ID:jiteshpunjabi,项目名称:movie-rest-api,代码行数:20,代码来源:views.py

示例7: addmovie

# 需要导入模块: from models import Movie [as 别名]
# 或者: from models.Movie import save [as 别名]
def addmovie(request):
    if request.method=='POST':
        form = MovieInfoForm(request.POST,request.FILES)
        if not form.is_valid():
            return render(request,'webuser/addmovie.html',{'form':form})
        else:
            moviename = form.cleaned_data.get('moviename')
            movieaddress = form.cleaned_data.get('movieaddress')
            downloadlink = form.cleaned_data.get('downloadlink')
            style = form.cleaned_data.get('style')
            language = form.cleaned_data.get('language')
            image = request.FILES['image']
            movie = Movie(moviename=moviename,movieaddress=movieaddress,downloadlink=downloadlink,
                          style=style,language=language,image=image,original=str(user.webuser.id))
            movie.save()
            messages.add_message(request,messages.SUCCESS,u'电影添加成功.')
    else:
        form = MovieInfoForm();
    return render(request,'webuser/addmovie.html',{'form':form})
开发者ID:Mouihena,项目名称:dnomovie,代码行数:21,代码来源:views.py

示例8: movie

# 需要导入模块: from models import Movie [as 别名]
# 或者: from models.Movie import save [as 别名]
def movie(id):
    
    if request.method == "GET":
        
        movie = _fetch_movie(id)
        if movie is not None:
            if request.is_xhr:
                return jsonify({"service_id":movie.service_id, "title": movie.title, "description": movie.description, "poster": movie.poster, "year": movie.year, "imdb_id": movie.imdb_id, "votes": movie.votes, "in_production": movie.being_made, "produced": movie.already_made, "facebook_uid": movie.facebook_uid, "facebook_name": movie.facebook_name})
            
            voters = _fetch_latest_votes(id)
            
            return render_template('single.html', movie=movie, image_path=settings.IMAGE_PATH, voters=voters)
    
    if request.method == "POST":
        form = MovieForm(request.form)
        if form.validate() is False:
            
            for error in form.errors:
                logging.info(error)
            
            return abort(500)
        
        if _validate_user(form.facebook_uid.data, form.facebook_token.data):
            
            movie = _fetch_movie(form.service_id.data)
            
            if movie is None:
                
                m = Movie(service_id=form.service_id.data, title=form.title.data, year=form.year.data.split("-")[0], poster=form.poster.data, description=form.description.data, imdb_id=form.imdb_id.data, facebook_uid=form.facebook_uid.data, facebook_name=form.facebook_name.data)
                m.save()
            
            return jsonify(result="success")
        
        return abort(500)
    
    return abort(404)
开发者ID:Skaggivara,项目名称:reboot,代码行数:38,代码来源:views.py

示例9: test_add_movie_using_json_model

# 需要导入模块: from models import Movie [as 别名]
# 或者: from models.Movie import save [as 别名]
 def test_add_movie_using_json_model(self):
     f = open('single_movie.json', 'r')
     m = Movie()
     m.add_using_json(f.read())
     m.save()
     self.assertEqual(Movie.objects.get(movie_name='three little pigs'),m)
开发者ID:jiteshpunjabi,项目名称:movie-rest-api,代码行数:8,代码来源:tests.py

示例10: add_movie

# 需要导入模块: from models import Movie [as 别名]
# 或者: from models.Movie import save [as 别名]
def add_movie(request):
    newmovie = Movie(title=request.POST['movie_title'])
    # when making new objects, always remember to save them
    newmovie.save()
    return HttpResponseRedirect('/movies')
开发者ID:sagi12-meet,项目名称:MEET-YL2,代码行数:7,代码来源:views.py


注:本文中的models.Movie.save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。