1+ import json
2+ import uuid
3+
4+ from flask import Blueprint , request
5+ from video_app .utils import logged_input , get_timestamp_now
6+ from video_app .validator import CreateVideoSchema , VideoSchema
7+ from video_app .models import Video
8+ from video_app .api .helper import send_error , send_result
9+ from video_app .extensions import db
10+
11+
12+ api = Blueprint ('videos' , __name__ )
13+
14+
15+ @api .route ('' , methods = ['GET' ])
16+ def search_videos ():
17+ """
18+ Search video api
19+ Requests params:
20+ keyword: string, optional
21+ Returns:
22+ list videos
23+ """
24+
25+ keyword = request .args .get ('keyword' , '' ).strip ()
26+ videos = Video .query .filter (Video .title .ilike (f'%{ keyword } %' )).all ()
27+ videos_dumped = VideoSchema (many = True ).dumps (videos )
28+ return send_result (data = json .loads (videos_dumped ))
29+
30+
31+ @api .route ('' , methods = ['POST' ])
32+ def create_new_video ():
33+ """
34+ Create new video API.
35+ Requests Body:
36+ title: string, require
37+ url: string, optional
38+ thumbnail_url: string, optional
39+ Returns:
40+ id of new video
41+ """
42+
43+ try :
44+ json_req = request .get_json ()
45+ except Exception as ex :
46+ return send_error (message = "Request Body incorrect json format: " + str (ex ), code = 442 )
47+
48+ logged_input (json .dumps (json_req ))
49+ if json_req is None :
50+ return send_error (message = 'Please check your json requests' , code = 442 )
51+
52+ # trim input body
53+ json_body = {}
54+ for key , value in json_req .items ():
55+ json_body .setdefault (key , str (value ).strip ())
56+
57+ # validate request body
58+ is_not_validate = CreateVideoSchema ().validate (json_body ) # Dictionary show detail error fields
59+ if is_not_validate :
60+ return send_error (data = is_not_validate , message = "Invalid params" )
61+
62+ title = json_body .get ("title" )
63+ url = json_body .get ("url" , "" )
64+ thumbnail_url = json_body .get ("thumbnail_url" , "" )
65+ _id = str (uuid .uuid4 ())
66+ # Store video to db
67+ new_video = Video (id = _id , title = title , url = url , thumbnail_url = thumbnail_url )
68+ db .session .add (new_video )
69+ db .session .commit ()
70+ data = {
71+ "video_id" : _id
72+ }
73+ return send_result (data )
0 commit comments