· 8 years ago · Feb 22, 2018, 01:30 PM
1from flask import Flask, render_template, request, url_for, redirect, session, escape, abort, g, jsonify
2from flask_restful import Resource, Api, fields, marshal_with, reqparse
3from functools import wraps
4from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth
5import json
6from flask_cors import CORS
7
8from werkzeug.wrappers import BaseRequest
9from werkzeug.wsgi import responder
10from werkzeug.exceptions import HTTPException, NotFound, Conflict
11from werkzeug.exceptions import BadRequest
12
13#++++++++++ mysql code +++++++++++++++++
14
15
16
17
18
19
20
21
22
23
24
25
26# errors = {
27# 'UserAlreadyExistsError': {
28# 'message': "A user with that username already exists.",
29# 'status': 409,
30# },
31# 'ResourceDoesNotExist': {
32# 'message': "A resource with that ID no longer exists.",
33# 'status': 410,
34# 'extra': "Any extra information you want.",
35# },
36# 'ResourceAlreadyExists': {
37# 'message': "This resource already exists.",
38# 'status': 700,
39# },
40# }
41
42errors = {
43 'UserAlreadyExistsError': {
44 'message': "A user with that username already exists.",
45 'status': 789,
46 },
47 'ResourceDoesNotExist': {
48 'message': "A resource with that ID no longer exists.",
49 'status': 410,
50 'extra': "Any extra information you want.",
51 },
52}
53
54class ResourceAlreadyExists(HTTPException):
55
56 # def __init__(self, name):
57 # self.name = name
58
59 code = 778
60 description = (
61 'Resource already exist.'
62 )
63
64 name = 'Very important name for my 777 code'
65
66
67import mysql.connector
68
69
70"""
71rms database connection handler
72"""
73def init_db():
74 cnx = mysql.connector.connect(user='', password='', database='rms_v1')
75 return cnx
76
77# cursor = cnx.cursor()
78
79# tomorrow = datetime.now().date() + timedelta(days=1)
80
81# add_employee = ("INSERT INTO employees "
82# "(first_name, last_name, hire_date, gender, birth_date) "
83# "VALUES (%s, %s, %s, %s, %s)")
84# add_salary = ("INSERT INTO salaries "
85# "(emp_no, salary, from_date, to_date) "
86# "VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")
87
88# data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))
89
90# # Insert new employee
91# cursor.execute(add_employee, data_employee)
92# emp_no = cursor.lastrowid
93
94# # Insert salary information
95# data_salary = {
96# 'emp_no': emp_no,
97# 'salary': 50000,
98# 'from_date': tomorrow,
99# 'to_date': date(9999, 1, 1),
100# }
101# cursor.execute(add_salary, data_salary)
102
103# # Make sure data is committed to the database
104# cnx.commit()
105
106
107# cursor = cnx.cursor()
108
109# query = ("SELECT first_name, last_name, hire_date FROM employees "
110# "WHERE hire_date BETWEEN %s AND %s")
111
112# hire_start = datetime.date(1999, 1, 1)
113# hire_end = datetime.date(1999, 12, 31)
114
115# cursor.execute(query, (hire_start, hire_end))
116
117# for (first_name, last_name, hire_date) in cursor:
118# print("{}, {} was hired on {:%d %b %Y}".format(
119# last_name, first_name, hire_date))
120
121# cursor.close()
122
123# cursor.close()
124# cnx.close()
125
126# from flask_mysqldb import MySQL
127
128 # cur.execute('''SELECT user, host FROM mysql.user''')
129 # rv = cur.fetchall()
130
131
132
133#++++++++++ mysql code end +++++++++++++
134
135basic_auth = HTTPBasicAuth()
136token_auth = HTTPTokenAuth('Bearer')
137auth = MultiAuth(basic_auth, token_auth)
138app = Flask(__name__)
139
140cors = CORS(app)
141api = Api(app)
142# mysql = MySQL(app)
143
144#cur = mysql.connection.cursor()
145#++++++++++++++ mysql start +++++++++++++++
146# mysql = MySQL()
147
148# MySQL configurations
149# app.config['MYSQL_DATABASE_USER'] = 'root'
150# app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
151# app.config['MYSQL_DATABASE_DB'] = 'alpha'
152# app.config['MYSQL_DATABASE_HOST'] = 'localhost'
153# mysql.init_app(app)
154
155
156
157# @app.route('/test')
158# def users():
159# cur = cnx.cursor()
160# #cur = mysql.connection.cursor()
161# cur.execute('''SELECT * FROM user''')
162# rv = cur.fetchall()
163# return str(rv)
164
165#++++++++++++++ mysql end +++++++++++++++++
166
167
168class Welcome(Resource):
169 """
170 #Welcome message
171 ----
172 This resource may be used to get version info
173
174 ##URL
175
176 /
177
178 ##Method
179
180 `GET`
181
182 ##URL Params
183
184 **None**
185
186 ##Data Params
187
188 **name**
189
190 ##Success Response
191
192 * **Code:** 200
193
194 **Content:** `{"message": "Welcome to Intelligent Restaurant Management REST API V1.0"}`
195
196 ##Error Response
197
198 * **Code:** 404 NOT FOUND
199
200 **Content:** `{ 'message' : "You are already registerd. Is there any problem signing in??" }`
201
202 OR
203
204 * **Code:** 401 UNAUTHORIZED
205
206 **Content:** `{ error : "You are unauthorized to make this request." }`
207
208 ##Sample Call
209
210 ~~~~
211 curl -X GET intiaz-test.appspot.com/
212 ~~~~
213 """
214 def get(self):
215
216 return {'message': 'Welcome to Intelligent Restaurant Management REST API V1.0.'}
217api.add_resource(Welcome, '/')
218
219
220class New_user_registration(Resource):
221 """
222 #New User Registration Resource
223 ----
224 This resource register a new user
225 Returns json data about a single user.
226
227 ##URL
228
229 /api/new_user_registraion
230
231 ##Method
232
233 `POST`
234
235 ##URL Params
236
237 **None**
238
239 ##Data Params
240
241 * **name** : *string*, Name of the user
242 * **email** : *string*, Email of the user
243 * **type_of_user** : *string*, Type of the user owner/manager/customer
244 * **home_town** : *string*, Home Town of the user
245 * **current_city** : *string*, Current city of the user
246 * **user_id** : *string*, user id of the user
247 * **password** : *string*, password of the user
248
249 ##Success Response
250
251 * **Code:** 200
252
253 **Content:** `{ 'message': 'You have been registerd successfully' }`
254
255 ##Error Response
256
257 * **Code:** 404 NOT FOUND
258
259 **Content:** `{ 'message' : "You are already registerd. Is there any problem signing in??" }`
260
261 OR
262
263 * **Code:** 401 UNAUTHORIZED
264
265 **Content:** `{ error : "You are unauthorized to make this request." }`
266
267 ##Sample Call
268
269 ~~~~
270
271 curl -X POST intiaz-test.appspot.com/api/new_user_registraion -d
272 {
273 'name':''
274 'email':'',
275 'type_of_user':'1',
276 'home_town':'',
277 'current_city':'',
278 'user_id':'',
279 'password':''
280 }
281 ~~~~
282 """
283
284 def post(self):
285 """
286 new user registration. There may be several roll of a user
287 """
288 try:
289 # Parse the arguments
290 parser = reqparse.RequestParser()
291
292 parser.add_argument('name', type=str, help='Email address to create user', required=True)
293 parser.add_argument('type_of_user', type=int, help='Email address to create user')
294 parser.add_argument('home_town', type=str, help='Password to create user')
295 parser.add_argument('current_city', type=str, help='Email address to create user')
296 parser.add_argument('email', type=str, help='Email address to create user')
297 parser.add_argument('user_id', type=int, help='Password to create user')
298 parser.add_argument('password', type=str, help='Password to create user')
299
300 args = parser.parse_args()
301
302 # user = User.get_by_id(args['email'])
303 # if user is not None:
304 # return {'message' : 'You are already registerd. Is there any problem signing in??'}
305
306 # user = User(name=args['name'],
307 # type_of_user=args['type_of_user'],
308 # home_town=args['home_town'],
309 # current_city=args['current_city'],
310 # email = args['email'],
311 # id = args['email'],
312 # password=args['password'])
313
314 # user.put()
315 #+++++++++++++++++++++ mysql database query +++++++++++++++++++
316 """
317 cur = mysql.connection.cursor()
318 cur.execute('''SELECT user, host FROM mysql.user''')
319 rv = cur.fetchall()
320 return str(rv)
321
322 add_employee = ("INSERT INTO employees "
323 "(first_name, last_name, hire_date, gender, birth_date) "
324 "VALUES (%s, %s, %s, %s, %s)")
325
326 data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))
327 cursor.execute(add_employee, data_employee)
328 cnx.commit()
329
330
331 add_employee = ("INSERT INTO employees "
332 "(first_name, last_name, hire_date, gender, birth_date) "
333 "VALUES (%s, %s, %s, %s, %s)")
334 add_salary = ("INSERT INTO salaries "
335 "(emp_no, salary, from_date, to_date) "
336 "VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")
337
338 data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))
339
340 # Insert new employee
341 cursor.execute(add_employee, data_employee)
342 emp_no = cursor.lastrowid
343
344 # Insert salary information
345 data_salary = {
346 'emp_no': emp_no,
347 'salary': 50000,
348 'from_date': tomorrow,
349 'to_date': date(9999, 1, 1),
350 }
351 cursor.execute(add_salary, data_salary)
352
353 # Make sure data is committed to the database
354 cnx.commit()
355
356 cursor.close()
357
358 #user table definition
359 CREATE TABLE user (
360 id INT NOT NULL AUTO_INCREMENT,
361 email CHAR(100),
362 name CHAR(100),
363 hometown CHAR(100),
364 current_city CHAR(100),
365 role ENUM('customer', 'restaurant_owner'),
366 password CHAR(100),
367 PRIMARY KEY(id)
368 ) ENGINE=INNODB;
369 """
370 cnx = init_db()
371 cursor = cnx.cursor()
372 query = ("SELECT * FROM user where email = %s")
373 cursor.execute(query, (args['email'],))
374
375 rv = cursor.fetchall()
376 if(len(rv)):
377 return{'message':'error',
378 'description': 'user already exist.'}
379
380 add_user = ("INSERT INTO user "
381 "(email, name, hometown, current_city, role, password)"
382 "VALUES (%s, %s, %s, %s, %s, %s)")
383
384 data_user = (args['email'], args['name'], args['home_town'], args['current_city'], 1, args['password'] )
385
386 cursor.execute(add_user, data_user)
387 emp_no = cursor.lastrowid
388 try:
389 cnx.commit()
390 except:
391 cnx.rollback()
392
393 cursor.close()
394
395 #+++++++++++++++++++++ mysql database query +++++++++++++++++++
396 # return {'message': {
397 # 'name': args['name'],
398 # 'email':args['email'],
399 # 'type_of_user':args['type_of_user'],
400 # 'home_town':args['home_town'],
401 # 'current_city':args['current_city'],
402 # 'user_id':args['email'],
403 # 'password':args['password']
404 # }
405 # }
406 return {'id': emp_no,
407 'status': 'success',
408 'description': 'You have been registered successfully.'}
409
410 except Exception as e:
411 return {'error': str(e)}
412
413api.add_resource(New_user_registration, '/api/new_user_registraion')
414
415
416from itsdangerous import (TimedJSONWebSignatureSerializer
417 as Serializer, BadSignature, SignatureExpired)
418
419
420@token_auth.verify_token
421def verify_token(token):
422 s = Serializer(app.config['SECRET_KEY'])
423 try:
424 data = s.loads(token)
425 except SignatureExpired:
426 return False # valid token, but expired
427 except BadSignature:
428 return False # invalid token
429
430
431 #g.user = User.get_by_id(data['id'])
432 cnx = init_db()
433 cursor = cnx.cursor(buffered=True)
434 query = ("SELECT * FROM user where id= %s and nonce= %s")
435 cursor.execute(query, (data['id'],data['nonce']))
436 rv = cursor.fetchone()
437
438 app.logger.info("verifying token...")
439 if(rv is None):
440 return False
441 g.uid = data['id']
442 g.rid = data['rid']
443 app.logger.info('Restaurant id: '+ str( g.rid))
444 # g.user = "mhsn06"
445 # g.nonce = data['nonce']
446 #return g.user.nonce == data['nonce']
447 return True
448
449@basic_auth.verify_password
450def verify_password(username, password):
451## user = None
452## if not username:
453 #user = User.get_by_id(username)
454 #user = "mhsn06"
455 cnx = init_db()
456 cursor = cnx.cursor(buffered=True)
457 query = ("SELECT * FROM user where email= %s and password= %s")
458 cursor.execute(query, (username,password))
459 rv = cursor.fetchone()
460 cursor.close()
461 app.logger.info("verifying password ...")
462 if(rv is None):
463 # g.uid = rv
464 return False
465 # g.uid = rv
466 g.uid = rv[0]
467 return True
468
469
470
471import string
472import random
473def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
474 return ''.join(random.choice(chars) for _ in range(size))
475
476
477def generate_auth_token(expiration = 6000):
478 s = Serializer(app.config['SECRET_KEY'], expires_in = expiration)
479 g.nonce = id_generator()
480 #self.put() #saving nonce to database
481 cnx = init_db()
482 cursor = cnx.cursor()
483 add_auth_user = ("UPDATE user SET nonce= %s WHERE id= %s")
484 data_auth_user = (g.nonce, g.uid)
485 cursor.execute(add_auth_user, data_auth_user)
486
487 rid = None
488 cursor = cnx.cursor()
489 query = ("SELECT restaurant_id FROM restaurant_ownership WHERE user_id= %s")
490 data = (g.uid,)
491 cursor.execute(query, data)
492 rows = cursor.fetchall()
493
494 if rows:
495 rid = rows[0][0]
496
497 try:
498 cnx.commit()
499 except:
500 cnx.rollback()
501 cursor.close()
502
503 return s.dumps({ 'id': g.uid, 'nonce': g.nonce, 'rid': rid })
504
505
506@app.route('/api/token')
507@auth.login_required
508def get_auth_token():
509 token = generate_auth_token()
510 return jsonify({ 'token': token.decode('ascii') })
511
512from flask import request
513import urllib2
514
515@app.route('/api/fbtoken' , methods=['GET', 'POST'])
516# @auth.login_required
517def test_fb_auth():
518 app.logger.info(request.args.get('token'))
519 appTokenUrl = 'https://graph.facebook.com/v2.8/oauth/access_token?client_id=1386803954727293&client_secret=07737f1e5025d80460f90596c172be0d&grant_type=client_credentials'
520
521 req = urllib2.Request(appTokenUrl)
522 response = urllib2.urlopen(req)
523 the_page = response.read()
524 # app.logger.info(json.loads(the_page)['access_token'])
525 # token = generate_auth_token()
526 url = 'https://graph.facebook.com/debug_token?input_token='+request.args.get('token')+'&access_token='+json.loads(the_page)['access_token']
527 # url += request.args.get('code')
528 req = urllib2.Request(url)
529 response = urllib2.urlopen(req)
530 the_page2 = response.read()
531 app.logger.info(the_page2)
532
533 url = 'https://graph.facebook.com/me?fields=cover,email,gender,first_name,last_name,locale,link,age_range,verified,updated_time,name&access_token='+request.args.get('token')
534 # url += request.args.get('code')
535 req = urllib2.Request(url)
536 response = urllib2.urlopen(req)
537 the_page = response.read()
538 app.logger.info(the_page)
539 return the_page
540 # app.logger.info(request.args.get('code'))
541 # return jsonify({
542 # 'data': request.args.get('token')})
543
544#custom token for firebase
545import python_jwt as jwt # Requires: pip install python-jwt
546import Crypto.PublicKey.RSA as RSA # Requires: pip install pycrypto
547from Crypto import Random
548
549import datetime
550
551# Get your service account's email address and private key from the JSON key file
552service_account_email = "firebase-adminsdk-rxtgv@intiaz-test.iam.gserviceaccount.com"
553private_key = RSA.importKey("-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDLMn9aRsPFyTr1\noTXsPX/fHm9fJbfe5x/8sxIYClu7A7z+jEAqXgbXCIOA/3Icc6sql40UMwBAT5Si\nygkpG0BlKOJBGna0zHNMwV0Mzz/AiV5819Lve2UwGw61om9HOBIlNu6+VEz1t8Ta\nEOmQ/By35ATbDYjQu8ViGSYnPtWAe5hwBq80wDnZctq0Z5z4eOBNS+FPhCD7rSsm\ngdvEvo0hWt1xJ330yZqzgzTP2l7QZs08jaZE3h3ZVBOdBcJMRGyUKeaXT0cEDnT6\nZ3dO9WLT4IsGv1TfZOxcvYbR96UGsmiKdHKLzVZpoe5RUkwK1PWUbhNfaPtCX0gm\nQV3SfdAHAgMBAAECggEARousnUoOM//OIXMrxm3/lBX78pukv5WcjF4bPQ9zk3UT\ny4gjytHELCm/hiypkGk0FuBw0X93adx3LSFZltToQXa1PocSiWil6xMC3Cyj5JOM\no2lGyXAczFvIepT/b0lvO05cCuY3peN8S30tqfFtgwZ+DRMg2d8nAwzaKyvsceNY\nBkdyafvyNvNXfzQcfKpmvciaorbdN8t62cZ1glq7Kf9zlnUOMGLbyQTyKdS43Pp8\nz8G3S+asNqMM5K1DcGG/UCOrkSwIGSrQH0VQgYDd/fBf467IYRa0GcULuohD6mrl\nLqMInlCPolpMrkkbuIzg5B/3d91E7KjqCdeDHsT4iQKBgQD7WxPQTJ7JV/CMxLjy\n+fsaD02L6ZFchR3btEdek9V5TBFYIzDBRy4alJLp3h57us9XJcZZf7IXtWyBnD4J\nIzlcDFcxkmqIHODfiTwTiCZ0W/udBdHcD2m3PsTNCNLoQz/qzK5jbXEdbUymyh22\njvwOUch+zd1KLXQVvAmBfU9WiwKBgQDO86Df/kfCUKN09fQiAKn/nxxKff91qcGn\nCM/YqnpHy2bS3EvbWBjntm2+BlM1b4qjIAKGo8dQCPoySqd50dgFYb+9o60Gwzs0\nriV8QAlXrluFG4G9iV4PF/7aIGiLLsZw/NWmgv1RmrqqBsCJzw4MoxJctTn0I9nZ\n00D5gQyX9QKBgDWaPqd1L4eQkWPzr91hIgN0r/zeWnl4id2InI+2xxeO+UPqfUM6\ngsJ4XLwy+h04wW68R4heiwQzVGhvgWtBb8IJf666oq1UO0Bwa7demZTG6OmbjB15\ny/mgESgIcbHGZaMU8zuQ40Z7QJVxFNURuP70weUI0eA3wUHBT+Wla33xAoGAXGjN\nXTfeMxZu5rss2EITpuEVcO3yNEgpAL0eklENaSGaOG3GMZuVA2Kifke0wBeegFi6\nyAQ567MWhX5waiUZoM2VIMkFag+jUFKyyliN02k31KgDtu6v4W2Fj0EJbZzlX26G\nuGOlWdsNnv6E2wRp8ZqfiGYkCrA3htyeFstZJEECgYEAx24kJ37FVG6dWU4VJbJd\nAxv8XL5O8r2ckOq37ltQL2DO0YmPOegecwLlEBiHEVPo/PplYucN3Q8P8+YkXl4q\npElkwbXN7ddpP/cYBn0iCDkr68ful+JY43EhPNA8f/1J2vcbic4MvUwogB5Vj/Kz\nyGYL8MCDYuCtrcvKcmGL+6w=\n-----END PRIVATE KEY-----\n")
554
555def create_custom_token(uid, is_premium_account):
556 #query for restaurant
557 #restaurents = Restaurant.query(Restaurant.owner == g.user.key)
558 restaurents = "jlakjdfljsaldkjfkjfkj";
559
560 try:
561 Random.atfork()
562 payload = {
563 "iss": service_account_email,
564 "sub": service_account_email,
565 "aud": "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
566 "uid": uid,
567 "claims": {
568 "premium_account": is_premium_account,
569 "restaurant" : restaurents, #.get().key.urlsafe(),
570 "role" : 1 #.type_of_user
571 }
572 }
573 exp = datetime.timedelta(minutes=60)
574 return jwt.generate_jwt(payload, private_key, "RS256", exp)
575 except Exception as e:
576 print "Error creating custom token: " + e.message
577 return e.message
578
579
580@app.route('/api/firebase_token')
581@auth.login_required
582def get_firebase_auth_token():
583 return jsonify({ 'token': create_custom_token('mhsn06', 'Test Premium Account') })
584
585
586#firebase token code ends here
587
588
589class restaurant(Resource):
590
591 @auth.login_required
592 def get(self, r_id=None):
593 cnx = init_db()
594 cursor = cnx.cursor()
595 query = ("SELECT * FROM restaurant where id = %s")
596 cursor.execute(query, (r_id,))
597 row = cursor.fetchone()
598 if row is None:
599 return{'error':'not found'}
600 return{'id': row[0],
601 'name':row[1],
602 'lat':row[2],
603 'lon':row[3],
604 'address':row[4],
605 'open_time':row[5],
606 'closed_time':row[6],
607 'has_air_condition':row[7],
608 'has_wifi':row[8],
609 'customer_capacity':row[9]}
610
611
612 @auth.login_required
613 def post(self, r_id=None):
614 try:
615 parser = reqparse.RequestParser()
616 parser.add_argument('name', type=str, help='Email address to create user', required=True)
617 parser.add_argument('city', type=str, help='Email address to create user')
618 parser.add_argument('capacity', type=int, help='Password to create user')
619 parser.add_argument('location', type=str, help='Email address to create user')
620 parser.add_argument('no_of_employees', type=int, help='Email address to create user')
621 args = parser.parse_args()
622 cnx = init_db()
623 cursor = cnx.cursor()
624 query = ("SELECT * FROM restaurant where name = %s")
625 cursor.execute(query, (args['name'],))
626
627 rv = cursor.fetchall()
628 if(len(rv)):
629 return{'message':'error',
630 'description': 'restaurant already exist.'}
631
632 add_restaurant = ("INSERT INTO restaurant "
633 "(name, lat, lon, address, open_time, closed_time, has_air_condition, has_wifi, customer_capacity)"
634 "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)")
635
636 data_restaurant = (args['name'], 78.43, -34.54, args['city'], 7, 22, True, True, args['capacity'])
637
638 cursor.execute(add_restaurant, data_restaurant)
639 restaurant_id = cursor.lastrowid
640
641 add_restaurant_own = ("INSERT INTO restaurant_ownership "
642 "(restaurant_id, user_id)"
643 "VALUES (%s, %s)")
644
645 data_restaurant_own = (restaurant_id,g.uid)
646 cursor.execute(add_restaurant_own, data_restaurant_own)
647
648 try:
649 cnx.commit()
650 except:
651 cnx.rollback()
652
653 cursor.close()
654
655
656 #+++++++++++++++++++++ mysql database query +++++++++++++++++++
657 return {'id': restaurant_id,
658 'status': 'success',
659 'description': 'You have been registered successfully.'}
660
661 except Exception as e:
662 return {'error': str(e)}
663
664 @auth.login_required
665 def delete(self, r_id=None):
666 """
667 general user should not delete restaurant info
668 """
669 pass
670
671api.add_resource(restaurant, '/api/restaurant','/api/restaurant/<int:r_id>',)
672
673#this resource is depricated
674# class Add_new_restaurent(Resource):
675# """
676# #Register a restaurant
677# ----
678# This resource register a restaurant
679
680# ##URL
681
682# /api/add_new_restaurent
683
684# ##Method
685
686# `POST`
687
688# ##URL Params
689
690# **None**
691
692
693# ##Data Params
694
695# * **name** : *string*, Name of the restaurant
696# * **city** : *string*, City of the restaurant
697# * **capacity** : *integer*, Number of customer can be served at a time
698# * **location** : *string*, Location of the restaurant
699# * **no_of_employees** : *integer*, Number of employees working in the restaurant
700
701# ##Success Response
702
703# * **Code:** 200
704
705# **Content:** `{ 'status': 'success' }`
706
707# ##Error Response
708
709# * **Code:** 404 NOT FOUND
710
711# **Content:** `{ 'message' : "You are already registerd. Is there any problem signing in??" }`
712
713# OR
714
715# * **Code:** 401 UNAUTHORIZED
716
717# **Content:** `{ error : "You are unauthorized to make this request." }`
718
719# ##Sample Call
720
721# ~~~~
722
723# curl -X POST intiaz-test.appspot.com/api/add_new_restaurent -d
724# {
725# 'name':'Riziqe'
726# 'city':'Rangpur',
727# 'capacity':'50',
728# 'location':'Bou Bazar',
729# 'no_of_employees':'10',
730# }
731# ~~~~
732# """
733
734# @auth.login_required
735# def post(self):
736# """
737# New restaurant registration, name, owner_id, capacity, location, no_of_employees, foods_id
738# """
739# try:
740# # Parse the arguments
741# parser = reqparse.RequestParser()
742
743# ## owner = ndb.StructuredProperty(User)
744# ## name = ndb.StringProperty()
745# ## city = ndb.StringProperty()
746# ## location = ndb.StringProperty() #lattitude, longitude
747# ## capacity = ndb.IntegerProperty()
748# ## no_of_employees = ndb.IntegerProperty()
749
750# parser.add_argument('name', type=str, help='Email address to create user', required=True)
751# parser.add_argument('city', type=str, help='Email address to create user')
752# parser.add_argument('capacity', type=int, help='Password to create user')
753# parser.add_argument('location', type=str, help='Email address to create user')
754# parser.add_argument('no_of_employees', type=int, help='Email address to create user')
755
756# args = parser.parse_args()
757
758
759# # restaurant = Restaurant(owner=g.user.key,
760# # name=args['name'],
761# # capacity=args['capacity'],
762# # location = args['location'],
763# # city = args['city'],
764# # no_of_employees = args['no_of_employees'])
765
766# # restaurant.put()
767# #+++++++++++++++++++++ mysql database query +++++++++++++++++++
768# """
769
770# #user table definition
771# CREATE TABLE restaurant (
772# id INT NOT NULL AUTO_INCREMENT,
773# name CHAR(100),
774# lat DECIMAL,
775# lon DECIMAL,
776# address CHAR(100),
777# open_time TIME,
778# closed_time TIME,
779# has_air_condition BIT,
780# has_wifi BIT,
781# customer_capacity INT UNSIGNED,
782# PRIMARY KEY(id)
783# ) ENGINE=INNODB;
784
785# CREATE TABLE restaurant_ownership (
786# id INT NOT NULL AUTO_INCREMENT,
787# restaurant_id INT NOT NULL,
788# user_id INT NOT NULL,
789
790# PRIMARY KEY(id),
791# INDEX (restaurant_id, user_id),
792
793# FOREIGN KEY (restaurant_id)
794# REFERENCES restaurant(id),
795
796# FOREIGN KEY (user_id)
797# REFERENCES user(id)
798# ) ENGINE=INNODB;
799# """
800# #check if restaurant already exist
801
802# cnx = init_db()
803# cursor = cnx.cursor()
804# query = ("SELECT * FROM restaurant where name = %s")
805# cursor.execute(query, (args['name'],))
806
807# rv = cursor.fetchall()
808# if(len(rv)):
809# return{'message':'error',
810# 'description': 'restaurant already exist.'}
811
812# add_restaurant = ("INSERT INTO restaurant "
813# "(name, lat, lon, address, open_time, closed_time, has_air_condition, has_wifi, customer_capacity)"
814# "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)")
815
816
817
818
819# data_restaurant = (args['name'], 78.43, -34.54, args['city'], 7, 22, True, True, args['capacity'])
820
821# cursor.execute(add_restaurant, data_restaurant)
822# restaurant_id = cursor.lastrowid
823
824# add_restaurant_own = ("INSERT INTO restaurant_ownership "
825# "(restaurant_id, user_id)"
826# "VALUES (%s, %s)")
827
828# data_restaurant_own = (restaurant_id,g.uid)
829# cursor.execute(add_restaurant_own, data_restaurant_own)
830
831# try:
832# cnx.commit()
833# except:
834# cnx.rollback()
835
836# cursor.close()
837
838
839# #+++++++++++++++++++++ mysql database query +++++++++++++++++++
840# return {'id': restaurant_id,
841# 'status': 'success',
842# 'description': 'You have been registered successfully.'}
843
844# except Exception as e:
845# return {'error': str(e)}
846
847# api.add_resource(Add_new_restaurent, '/api/add_new_restaurent')
848
849
850class Get_restaurant_list(Resource):
851 """
852 #Get the list of foods
853 ----
854 This resource get the list of foods
855
856 ##URL
857
858 /api/get_available_foods_list
859
860 ##Method
861
862 `GET`
863
864 ##URL Params
865
866 **None**
867
868 ##Data Params
869
870 * **name** : *string*, Email of the user
871
872 ##Success Response
873
874 * **Code:** 200
875
876 **Content:** `{ "foods": [
877 {
878 "food_catagories": "10",
879 "name": "Biriani",
880 "img_url": "http://img.url",
881 "price": 70
882 },
883 {
884 "food_catagories": "10",
885 "name": "Kacchi Biriani",
886 "img_url": "http://img.url",
887 "price": 70
888 },
889 {
890 "food_catagories": "10",
891 "name": "Biriani",
892 "img_url": "http://img.url",
893 "price": 70
894 }
895 ] }`
896
897 ##Error Response
898
899 * **Code:** 404 NOT FOUND
900
901 **Content:** `{ 'message' : "You are already registerd. Is there any problem signing in??" }`
902
903 OR
904
905 * **Code:** 401 UNAUTHORIZED
906
907 **Content:** `{ error : "You are unauthorized to make this request." }`
908
909 ##Sample Call
910
911 ~~~~
912
913 curl -X GET intiaz-test.appspot.com/api/get_available_foods_list
914 ~~~~
915
916
917 CREATE TABLE restaurant_ownership (
918 id INT NOT NULL AUTO_INCREMENT,
919 restaurant_id INT NOT NULL,
920 user_id INT NOT NULL,
921
922 PRIMARY KEY(id),
923 INDEX (restaurant_id, user_id),
924
925 FOREIGN KEY (restaurant_id)
926 REFERENCES restaurant(id),
927
928 FOREIGN KEY (user_id)
929 REFERENCES user(id)
930 ) ENGINE=INNODB;
931
932 """
933 @auth.login_required
934 def get(self):
935 cnx = init_db()
936 cursor = cnx.cursor()
937 query = ("SELECT * FROM restaurant WHERE id in ("
938 "SELECT restaurant_id FROM restaurant_ownership where user_id = %s)")
939 cursor.execute(query, (g.uid,))
940
941 #restaurents = Restaurant.query(Restaurant.owner == g.user.key)
942 a = []
943 for r in cursor:
944 #a.append(r[0])
945 a.append({
946 'id': r[0],
947 'name': r[1],
948 'lat': float(r[2]),
949 'lon': float(r[3]),
950 'address':r[4],
951 'open_time': str(r[5]),
952 'closed_time':str(r[6]),
953 'has_air_condition':r[7],
954 'has_wifi':r[8],
955 'customer_capacity':r[9]
956 })
957 #return {'test': foods}
958 try:
959 cnx.commit()
960 except:
961 cnx.rollback()
962 cursor.close()
963 return {'restaurants':a}
964
965api.add_resource(Get_restaurant_list, '/api/get_restaurant_list')
966
967
968class Restaurant_suggestions(Resource):
969 """
970 #Get the list of foods
971 ----
972 This resource get the list of foods
973
974 ##URL
975
976 /api/get_available_foods_list
977
978 ##Method
979
980 `GET`
981
982 ##URL Params
983
984 **None**
985
986 ##Data Params
987
988 * **name** : *string*, Email of the user
989
990 ##Success Response
991
992 * **Code:** 200
993
994 **Content:** `{ "foods": [
995 {
996 "food_catagories": "10",
997 "name": "Biriani",
998 "img_url": "http://img.url",
999 "price": 70
1000 },
1001 {
1002 "food_catagories": "10",
1003 "name": "Kacchi Biriani",
1004 "img_url": "http://img.url",
1005 "price": 70
1006 },
1007 {
1008 "food_catagories": "10",
1009 "name": "Biriani",
1010 "img_url": "http://img.url",
1011 "price": 70
1012 }
1013 ] }`
1014
1015 ##Error Response
1016
1017 * **Code:** 404 NOT FOUND
1018
1019 **Content:** `{ 'message' : "You are already registerd. Is there any problem signing in??" }`
1020
1021 OR
1022
1023 * **Code:** 401 UNAUTHORIZED
1024
1025 **Content:** `{ error : "You are unauthorized to make this request." }`
1026
1027 ##Sample Call
1028
1029 ~~~~
1030
1031 curl -X GET intiaz-test.appspot.com/api/get_available_foods_list
1032 ~~~~
1033 """
1034 # @auth.login_required
1035 def get(self):
1036 # foods = Food.query(Food.name == foodname)
1037 # a = []
1038 # for f in foods:
1039 # a.append(f.to_dict())
1040 #return {'test': foods}
1041 parser = reqparse.RequestParser()
1042 parser.add_argument('name', type=str, help='Enter Restaurant Name', required=True)
1043 args = parser.parse_args()
1044
1045 cnx = init_db()
1046 cursor = cnx.cursor(buffered=True)
1047 query = ("SELECT * FROM restaurant where name like %s")
1048
1049 cursor.execute(query, ("%" + args['name'] + "%",))
1050 a = []
1051 for row in cursor:
1052 a.append({
1053 'name':row[1],
1054 'id': row[0]
1055 })
1056 # print("{}, {} was hired on {:%d %b %Y}".format(
1057 # last_name, first_name, hire_date))
1058
1059 try:
1060 cnx.commit()
1061 except:
1062 cnx.rollback()
1063 cursor.close()
1064
1065
1066 #+++++++++++++++++++++ mysql database query +++++++++++++++++++
1067 return {'restaurants': a}
1068
1069api.add_resource(Restaurant_suggestions, '/api/restaurant_suggestion')
1070
1071#This resource is depricated
1072# class Add_employee(Resource):
1073# """
1074# #Add employee to the restaurant
1075# ----
1076# This resource send request to employees
1077
1078# ##URL
1079
1080# /api/add_new_employee
1081
1082# ##Method
1083
1084# `POST`
1085
1086# ##URL Params
1087
1088# **None**
1089
1090
1091# ##Data Params
1092
1093# * **restaurant** : *int*, Id of the restaurant. see get registered restaurant list with id
1094# * **email** : *string*, Email of the employee
1095# * **status** : *int*, Accept=1/Denied=0/Pending=2 of the user
1096
1097# ##Success Response
1098
1099# * **Code:** 200
1100
1101# **Content:** `{ 'Status': 'success' }`
1102
1103# ##Error Response
1104
1105# * **Code:** 404 NOT FOUND
1106
1107# **Content:** `{ 'message' : "You are already registerd. Is there any problem signing in??" }`
1108
1109# OR
1110
1111# * **Code:** 401 UNAUTHORIZED
1112
1113# **Content:** `{ error : "You are unauthorized to make this request." }`
1114
1115# ##Sample Call
1116
1117# ~~~~
1118
1119# curl -X GET intiaz-test.appspot.com/api/add_new_employee -d
1120# {
1121# 'restaurant':'5184609641824256'
1122# 'email':'mhsn06@gmail.com'
1123# }
1124# ~~~~
1125# """
1126# @auth.login_required
1127# def post(self):
1128# try:
1129# # Parse the arguments
1130# parser = reqparse.RequestParser()
1131
1132# parser.add_argument('restaurant', type=int, help='Email address to create user', required=True)
1133# parser.add_argument('email', type=str, help='Email address to create user')
1134
1135# parser.add_argument('designation', type=str, help='Email address to create user')
1136
1137# #parser.add_argument('status', type=int, help='Password to create user')
1138
1139
1140# args = parser.parse_args()
1141
1142
1143# # res = Restaurant.get_by_id(args['restaurant'])
1144# # staff_id = User.get_by_id(args['email'])
1145
1146# # emp = Employee(restaurant=res.key,
1147# # employee=staff_id.key,
1148# # status=2)
1149
1150# # emp.put()
1151# #+++++++++++++++++++++ mysql database query +++++++++++++++++++
1152# """
1153
1154# #user table definition
1155# CREATE TABLE restaurant_employees (
1156# id INT NOT NULL AUTO_INCREMENT,
1157# restaurant_id INT NOT NULL,
1158# user_id INT NOT NULL,
1159# employee_role ENUM('manager', 'waiter', 'cashier', 'cook','server', 'cleaner'),
1160
1161# PRIMARY KEY(id),
1162# INDEX (restaurant_id, user_id),
1163
1164# FOREIGN KEY (restaurant_id)
1165# REFERENCES restaurant(id),
1166
1167# FOREIGN KEY (user_id)
1168# REFERENCES user(id)
1169# ) ENGINE=INNODB;
1170# """
1171# cnx = init_db()
1172# cursor = cnx.cursor(buffered=True)
1173# query = ("SELECT * FROM user where email= %s")
1174# cursor.execute(query, (args['email'],))
1175
1176# rv = cursor.fetchone()
1177# if(rv is None):
1178# #user does not exist
1179# #create a new user
1180# #send mail with a validation link
1181# add_user = ("INSERT INTO user "
1182# "(email, password)"
1183# "VALUES (%s, %s)")
1184
1185# data_user = (args['email'], "j2l432k4hhkjk14234(SSFWw423" )
1186
1187# cursor.execute(add_user, data_user)
1188
1189# id = cursor.lastrowid
1190# else:
1191# id = rv[0]
1192
1193# #for (id) in rv:
1194
1195# #row = rv[0]
1196# #id = rv[0]
1197# # return {'debug' : id}
1198
1199# cursor = cnx.cursor(buffered=True)
1200# query2 = ("SELECT * FROM restaurant_employees where restaurant_id = %s and user_id= %s")
1201
1202# #get user's desired restaurant id
1203# cursor.execute(query2, (args['restaurant'], id))
1204
1205# rv = cursor.fetchall()
1206# #return {'debug' : rv}
1207# if(len(rv)):
1208# return{'message':'error',
1209# 'description': 'Employee already exist.'}
1210
1211# add_employee = ("INSERT INTO restaurant_employees "
1212# "(restaurant_id, user_id, employee_role)"
1213# "VALUES (%s, %s, %s)")
1214
1215# data_employee = (args['restaurant'], id, args['designation'])
1216
1217# cursor.execute(add_employee, data_employee)
1218# employee_id = cursor.lastrowid
1219# try:
1220# cnx.commit()
1221# except:
1222# cnx.rollback()
1223
1224# cursor.close()
1225
1226
1227# #+++++++++++++++++++++ mysql database query +++++++++++++++++++
1228# return {'id': employee_id,
1229# 'status': 'success',
1230# 'description': 'New employee has been recruited successfully'}
1231
1232# except Exception as e:
1233# return {'error': str(e)}
1234
1235# api.add_resource(Add_employee, '/api/add_new_employee')
1236
1237class Employee(Resource):
1238
1239 @auth.login_required
1240 def delete(self, employee_id=None):
1241 """
1242 Delete an employee
1243 """
1244 cnx = init_db()
1245 cursor = cnx.cursor()
1246 query = ("DELETE FROM restaurant_employees WHERE id = %s")
1247 cursor.execute(query, (employee_id,))
1248
1249 try:
1250 cnx.commit()
1251 return {'message': 'success'}
1252 except Exception as e:
1253 cnx.rollback()
1254 return {'message': 'failed ' + str(e)}
1255 finally:
1256 cursor.close()
1257
1258 @auth.login_required
1259 def post(self, employee_id=None):
1260 """
1261 update employee details
1262 """
1263 parser = reqparse.RequestParser()
1264
1265 parser.add_argument('restaurant', type=int, help='Email address to create user', required=True)
1266
1267 parser.add_argument('designation', type=str, help='Email address to create user')
1268 parser.add_argument('status', type=str, help='Email address to create user')
1269
1270
1271 args = parser.parse_args()
1272
1273
1274
1275 cnx = init_db()
1276 cursor = cnx.cursor()
1277 if employee_id is not None:
1278
1279 query = ("UPDATE restaurant_employees SET employee_role= %s, restaurant_id= %s WHERE id = %s")
1280 cursor.execute(query, (args['designation'], args['restaurant'] ,employee_id))
1281
1282 try:
1283 cnx.commit()
1284 return {
1285 'message': 'success'}
1286 except Exception as e:
1287 cnx.rollback()
1288 return {'message': 'failed ' + str(e)}
1289 finally:
1290 cursor.close()
1291
1292 else:
1293 query = ("INSERT INTO restaurant_employees (restaurant_id,user_id, employee_role) VALUES (%s, %s, %s)")
1294 #todo: replace it with user id dynamically
1295 dummy_user_id=1
1296 cursor.execute(query, (g.rid, dummy_user_id, args['designation']))
1297 employee_id = cursor.lastrowid
1298 try:
1299 cnx.commit()
1300 return {'id': employee_id,
1301 'message': 'success'}
1302 except Exception as e:
1303 cnx.rollback()
1304 return {'message': 'failed ' + str(e)}
1305 finally:
1306 cursor.close()
1307
1308api.add_resource(Employee,'/api/employee', '/api/employee/<int:employee_id>')
1309
1310
1311class Employees_list(Resource):
1312
1313 """
1314 CREATE TABLE restaurant_employees (
1315 id INT NOT NULL AUTO_INCREMENT,
1316 restaurant_id INT NOT NULL,
1317 user_id INT NOT NULL,
1318 employee_role ENUM('manager', 'waiter', 'cashier', 'cook','server', 'cleaner'),
1319
1320 PRIMARY KEY(id),
1321 INDEX (restaurant_id, user_id),
1322
1323 FOREIGN KEY (restaurant_id)
1324 REFERENCES restaurant(id),
1325
1326 FOREIGN KEY (user_id)
1327 REFERENCES user(id)
1328 ) ENGINE=INNODB;
1329
1330 """
1331
1332 @auth.login_required
1333 def get(self):
1334 cnx = init_db()
1335 cursor = cnx.cursor()
1336 #select * from user right join restaurant_employees on user.id = restaurant_employees.user_id where restaurant_id in (select restaurant_id from restaurant_ownership where user_id = 1);
1337
1338 query = ("SELECT * FROM user RIGHT JOIN restaurant_employees ON user.id=restaurant_employees.user_id WHERE restaurant_id in ("
1339 "SELECT restaurant_id FROM restaurant_ownership where user_id = %s)")
1340
1341 cursor.execute(query, (g.uid,))
1342
1343 employees=[]
1344 for r in cursor:
1345 employees.append({
1346 'id': r[8],
1347 'name': r[2],
1348 'email':r[1],
1349 'role':r[11]
1350 })
1351 try:
1352 cnx.commit()
1353 except:
1354 cnx.rollback()
1355 cursor.close()
1356 return{'employess': employees}
1357
1358api.add_resource(Employees_list, '/api/list_employees')
1359
1360# This resource is depricated
1361# class Add_new_food(Resource):
1362# """
1363# #Register a food
1364# ----
1365# This resource register a new food
1366
1367# ##URL
1368
1369# /api/add_new_food
1370
1371# ##Method
1372
1373# `POST`
1374
1375# ##URL Params
1376
1377# **None**
1378
1379# ##Data Params
1380
1381# * **name** : *string*, Name of the food
1382# * **img_url** : *string*, Image of the food
1383# * **food_catagories** : *string*, Name of the food catagories
1384# * **price** : *int*, price of the food
1385
1386# ##Success Response
1387
1388# * **Code:** 200
1389
1390# **Content:** `{ 'Status':'success' }`
1391
1392# ##Error Response
1393
1394# * **Code:** 404 NOT FOUND
1395
1396# **Content:** `{ 'message' : "You are already registerd. Is there any problem signing in??" }`
1397
1398# OR
1399
1400# * **Code:** 401 UNAUTHORIZED
1401
1402# **Content:** `{ error : "You are unauthorized to make this request." }`
1403
1404# ##Sample Call
1405
1406# ~~~~
1407
1408# curl -X GET intiaz-test.appspot.com/api/add_new_food -d
1409# {
1410# 'name':'Chicken Biriani'
1411# 'img_url':'http://img.url',
1412# 'food_catagories':'Biriani',
1413# 'price':'70'
1414# }
1415# ~~~~
1416# """
1417
1418# @auth.login_required
1419# def post(self):
1420# """
1421# Test This function does something.
1422
1423# :param name: The name to use.
1424# :type name: str.
1425# :param state: Current state to be in.
1426# :type state: bool.
1427# :returns: int -- the return code.
1428# :raises: AttributeError, KeyError
1429
1430# """
1431# try:
1432# # Parse the arguments
1433# parser = reqparse.RequestParser()
1434
1435# parser.add_argument('name', type=str, help='Email address to create user', required=True)
1436# parser.add_argument('img_url', type=str, help='Email address to create user')
1437# parser.add_argument('food_catagories', type=str, help='Password to create user')
1438# parser.add_argument('price', type=int, help='Email address to create user')
1439
1440# args = parser.parse_args()
1441
1442
1443# # food = Food(name=args['name'],
1444# # img_url=args['img_url'],
1445# # food_catagories=args['food_catagories'],
1446# # price = args['price'])
1447
1448# # key = food.put()
1449# # r = key.get()
1450# #return {'Status': r.name}
1451# #+++++++++++++++++++++ mysql database query +++++++++++++++++++
1452# """
1453
1454# #food table definition
1455# CREATE TABLE foods (
1456# id INT NOT NULL AUTO_INCREMENT,
1457# name CHAR(100),
1458# category CHAR(100),
1459# price DECIMAL,
1460# image_url CHAR(100),
1461# PRIMARY KEY(id)
1462# ) ENGINE=INNODB;
1463# """
1464# cnx = init_db()
1465# cursor = cnx.cursor()
1466# query = ("SELECT * FROM foods where name = %s")
1467# cursor.execute(query, (args['name'],))
1468
1469# rv = cursor.fetchall()
1470# if(len(rv)):
1471# return{'message':'error',
1472# 'description': 'food already exist.'}
1473
1474# add_food = ("INSERT INTO foods "
1475# "(name, category, price, image_url)"
1476# "VALUES (%s, %s, %s, %s)")
1477
1478# data_food = (args['name'], args['food_catagories'], args['price'], args['img_url'] )
1479
1480# cursor.execute(add_food, data_food)
1481# food_id = cursor.lastrowid
1482# try:
1483# cnx.commit()
1484# except:
1485# cnx.rollback()
1486
1487# cursor.close()
1488
1489
1490# #+++++++++++++++++++++ mysql database query +++++++++++++++++++
1491# return {'id': food_id,
1492# 'status': 'success',
1493# 'description': 'Your food have been added successfully.'}
1494
1495# except Exception as e:
1496# return {'error': str(e)}
1497
1498# api.add_resource(Add_new_food, '/api/add_new_food')
1499
1500class food(Resource):
1501 @auth.login_required
1502 def get(self, food_id=None):
1503 try:
1504 cnx = init_db()
1505 cursor = cnx.cursor()
1506 query = ("SELECT * FROM foods where id = %s")
1507 cursor.execute(query, (food_id,))
1508 row = cursor.fetchone()
1509
1510 cnx.commit()
1511 cursor.close()
1512 if(row is None):
1513 return{'error': 'You might have missed id or commited sin.'}
1514 #+++++++++++++++++++++ mysql database query +++++++++++++++++++
1515 return {'id': row[0],
1516 'name': row[1],
1517 'category': row[2],
1518 'image_url':row[3]}
1519 except Exception as e:
1520 return {'error': str(e)}
1521
1522 @auth.login_required
1523 def post(self, food_id=None):
1524 try:
1525 # Parse the arguments
1526 parser = reqparse.RequestParser()
1527
1528 parser.add_argument('name', type=str, help='Email address to create user', required=True)
1529 parser.add_argument('img_url', type=str, help='Email address to create user')
1530 parser.add_argument('food_catagories', type=str, help='Password to create user')
1531 # parser.add_argument('price', type=int, help='Email address to create user')
1532 args = parser.parse_args()
1533
1534 cnx = init_db()
1535 cursor = cnx.cursor()
1536 query = ("SELECT * FROM foods where name = %s")
1537 cursor.execute(query, (args['name'],))
1538
1539 rv = cursor.fetchall()
1540 if(len(rv)):
1541 return{'message':'error',
1542 'description': 'food already exist.'}
1543
1544 add_food = ("INSERT INTO foods "
1545 "(name, category, image_url)"
1546 "VALUES (%s, %s, %s)")
1547
1548 data_food = (args['name'], args['food_catagories'], args['img_url'] )
1549
1550 cursor.execute(add_food, data_food)
1551 food_id = cursor.lastrowid
1552
1553 cnx.commit()
1554 cursor.close()
1555
1556 #+++++++++++++++++++++ mysql database query +++++++++++++++++++
1557 return {'id': food_id,
1558 'status': 'success',
1559 'description': 'Your food have been added successfully.'}
1560 except Exception as e:
1561 return {'error': str(e)}
1562
1563 def delete(self, food_id):
1564 """
1565 user should not delete food
1566 """
1567 pass
1568
1569api.add_resource(food, '/api/food/<int:food_id>','/api/food')
1570
1571
1572class restaurant_menu_item(Resource):
1573 """
1574
1575 """
1576 @auth.login_required
1577 def get(self, item_id):
1578 """
1579 return single item
1580 """
1581 cnx = init_db()
1582 cursor = cnx.cursor(buffered=True)
1583 query = ("SELECT * FROM restaurant_menu where id= %s")
1584 cursor.execute(query, (item_id,))
1585
1586 rv = cursor.fetchone()
1587 if(rv is None):
1588 raise BadRequest('No such menu item exist.')
1589 # id = rv[0]
1590 #return id
1591
1592 return {'id':rv[0],
1593 'restaurant_id':rv[1],
1594 'food_id':rv[2],
1595 'available_today_status':rv[3]}
1596
1597 @auth.login_required
1598 def post(self, item_id=None):
1599 """
1600 create or update a new item
1601 TODO: update
1602 """
1603 # essential data
1604 try:
1605 parser = reqparse.RequestParser()
1606
1607 # parser.add_argument('restaurant_id', type=int, help='enter restaurant id', required=True)
1608 parser.add_argument('food_name', type=str, help='Email address to create user')
1609 parser.add_argument('food_status', type=str, help='Email address to create user')
1610 parser.add_argument('price', type=str, help='Email address to create user')
1611
1612 args = parser.parse_args()
1613
1614 #database
1615 cnx = init_db()
1616 cursor = cnx.cursor(buffered=True)
1617 query = ("SELECT * FROM foods where name= %s")
1618 cursor.execute(query, (args['food_name'],))
1619
1620 rv = cursor.fetchone()
1621
1622 except Exception as e:
1623 return {'error': str(e)}
1624
1625 if(rv is None):
1626 raise BadRequest('The food does not exist.')
1627
1628
1629 #getting id of item
1630 id = rv[0]
1631
1632 #check if already exist on menu
1633 cursor = cnx.cursor(buffered=True)
1634 query2 = ("SELECT * FROM restaurant_menu where restaurant_id = %s and food_id= %s")
1635 cursor.execute(query2, (g.rid, id))
1636 rv = cursor.fetchall()
1637 if(len(rv)):
1638 raise Conflict(description="Menu Item already exist.")
1639
1640 #adding item to menu
1641 cursor = cnx.cursor(buffered=True)
1642 add_item = ("INSERT INTO restaurant_menu "
1643 "(restaurant_id, food_id, price, available_today_status)"
1644 "VALUES (%s, %s, %s, %s)")
1645
1646 data_item = (g.rid, id,args['price'], args['food_status'])
1647
1648 cursor.execute(add_item, data_item)
1649 item_id = cursor.lastrowid
1650 try:
1651 cnx.commit()
1652 return {'id': item_id,
1653 'status': 'success',
1654 'description': 'New Item has been added to menu successfully'}
1655 except:
1656 cnx.rollback()
1657 finally:
1658 cursor.close()
1659
1660
1661
1662 @auth.login_required
1663 def delete(self, item_id):
1664 """
1665 delete an item
1666 """
1667 if(item_id is None):
1668 return{'error': 'failed',
1669 'description': 'no item to deleted'}
1670 try:
1671 cnx = init_db()
1672 cursor = cnx.cursor(buffered=True)
1673 query = ("DELETE FROM restaurant_menu where id= %s")
1674 cursor.execute(query, (item_id,))
1675
1676 try:
1677 cnx.commit()
1678 return {
1679 'status': 'success',
1680 'description': 'Item has been deleted from menu successfully'}
1681 except:
1682 cnx.rollback()
1683 finally:
1684 cursor.close()
1685 except Exception as e:
1686 return {'error': str(e)}
1687
1688api.add_resource(restaurant_menu_item, '/api/menu_item/<int:item_id>','/api/menu_item')
1689
1690
1691class menu_item_list(Resource):
1692
1693 @auth.login_required
1694 def get(self):
1695 """
1696 return item(menu_id, name, price, status)
1697 """
1698 cnx = init_db()
1699 cursor = cnx.cursor()
1700 query = "SELECT restaurant_menu.id, restaurant_menu.price, restaurant_menu.available_today_status, foods.name FROM restaurant_menu LEFT JOIN foods ON restaurant_menu.food_id=foods.id WHERE restaurant_menu.restaurant_id=%s"
1701
1702 data =(g.rid,)
1703 cursor.execute(query, data)
1704
1705
1706 items = []
1707
1708 for row in cursor:
1709 items.append({
1710 "menu_item_id": row[0],
1711 "item_name":row[3],
1712 "item_price":row[1],
1713 "item_status":row[2]
1714 })
1715 return{'items' : items}
1716
1717 def post(self):
1718 pass
1719 def delete(self):
1720 pass
1721
1722api.add_resource(menu_item_list,'/api/menu_item_list')
1723
1724# class Select_food(Resource):
1725# """
1726# #Select food for a restaurent
1727# ----
1728# This resource bind food with restaurant
1729
1730# ##URL
1731
1732# /api/select_food
1733
1734# ##Method
1735
1736# `POST`
1737
1738# ##URL Params
1739
1740# **None**
1741
1742# ##Data Params
1743
1744# * **restaurant_id** : *int*, id of the restaurant. see get restaurant list
1745# * **food_id** : *int*, id of the food. see get food list
1746# * **food_status** : *int*, available today = 1/ Not available = 0
1747
1748# ##Success Response
1749
1750# * **Code:** 200
1751
1752# **Content:** `{ 'status': 'success' }`
1753
1754# ##Error Response
1755
1756# * **Code:** 404 NOT FOUND
1757
1758# **Content:** `{ 'status': 'Failed',
1759# 'message': 'Food already added.'}`
1760
1761# OR
1762
1763# * **Code:** 401 UNAUTHORIZED
1764
1765# **Content:** `{ error : "You are unauthorized to make this request." }`
1766
1767# ##Sample Call
1768
1769# ~~~~
1770
1771# curl -X GET intiaz-test.appspot.com/api/select_food -d
1772# {
1773# 'restaurant_id':'5184609641824256'
1774# 'food_name':'kabab',
1775# 'food_status':'1'
1776# }
1777# ~~~~
1778# """
1779
1780# ## @auth.login_required
1781# ## def get(self):
1782# ## return {'welcome_message': 'authenticate user'}
1783
1784# @auth.login_required
1785# def post(self):
1786# """
1787# Test This function does something.
1788
1789# :param name: The name to use.
1790# :type name: str.
1791# :param state: Current state to be in.
1792# :type state: bool.
1793# :returns: int -- the return code.
1794# :raises: AttributeError, KeyError
1795# food_id = ndb.KeyProperty(kind=Food)
1796# restaurant_id = ndb.KeyProperty(kind=Restaurant)
1797# food_status = ndb.IntegerProperty()
1798
1799# """
1800# try:
1801# # Parse the arguments
1802# parser = reqparse.RequestParser()
1803
1804# parser.add_argument('restaurant_id', type=int, help='enter restaurant id', required=True)
1805# parser.add_argument('food_name', type=str, help='Email address to create user')
1806# parser.add_argument('food_status', type=int, help='Email address to create user')
1807
1808# args = parser.parse_args()
1809
1810
1811# # restaurant = Restaurant.get_by_id(args['restaurant_id'])
1812
1813# # #check if food already added.
1814# # selected_food_query = Selected_foods.query(Selected_foods.food_id == ndb.Key(Food, args['food_id']))
1815# # q = selected_food_query.get()
1816# # if q is not None:
1817# # return {'status': 'Failed',
1818# # 'message': 'Food already selected.'}
1819
1820# # selected_food = Selected_foods(
1821# # food_id=food.key,
1822# # restaurant_id=restaurant.key,
1823# # food_status = args['food_status'])
1824
1825# # selected_food.put()
1826# #+++++++++++++++++++++ mysql database query +++++++++++++++++++
1827# """
1828
1829# #food table definition
1830# CREATE TABLE restaurant_menu (
1831# id INT NOT NULL AUTO_INCREMENT,
1832# restaurant_id INT NOT NULL,
1833# food_id INT NOT NULL,
1834# available_today_status ENUM('available', 'unavailable'),
1835
1836# PRIMARY KEY(id),
1837# INDEX (restaurant_id, food_id),
1838
1839# FOREIGN KEY (restaurant_id)
1840# REFERENCES restaurant(id),
1841
1842# FOREIGN KEY (food_id)
1843# REFERENCES food(id)
1844# ) ENGINE=INNODB;
1845# """
1846# cnx = init_db()
1847# cursor = cnx.cursor(buffered=True)
1848# query = ("SELECT * FROM foods where name= %s")
1849# cursor.execute(query, (args['food_name'],))
1850
1851# rv = cursor.fetchone()
1852# if(len(rv) is None):
1853# return {'message':'error',
1854# 'description': 'food does not exist.'}
1855# id = rv[0]
1856# #return id
1857
1858# cursor = cnx.cursor(buffered=True)
1859# query2 = ("SELECT * FROM restaurant_menu where restaurant_id = %s and food_id= %s")
1860
1861# cursor.execute(query2, (args['restaurant_id'], id))
1862
1863# rv = cursor.fetchall()
1864# #return {'debug' : rv}
1865# if(len(rv)):
1866# return{'message':'error',
1867# 'description': 'Food already added to menu.'}
1868
1869# cursor = cnx.cursor(buffered=True)
1870# add_item = ("INSERT INTO restaurant_menu "
1871# "(restaurant_id, food_id, available_today_status)"
1872# "VALUES (%s, %s, %s)")
1873
1874# data_item = (args['restaurant_id'], id, 'available')
1875
1876# cursor.execute(add_item, data_item)
1877# item_id = cursor.lastrowid
1878# try:
1879# cnx.commit()
1880# except:
1881# cnx.rollback()
1882# cursor.close()
1883
1884
1885# #+++++++++++++++++++++ mysql database query +++++++++++++++++++
1886# return {'id': item_id,
1887# 'status': 'success',
1888# 'description': 'New food has been added to menu successfully'}
1889
1890# except Exception as e:
1891# return {'error': str(e)}
1892
1893# api.add_resource(Select_food, '/api/select_food')
1894
1895
1896# class Get_available_foods_list(Resource):
1897# """
1898# #Get the list of foods
1899# ----
1900# This resource get the list of foods
1901
1902# ##URL
1903
1904# /api/get_available_foods_list
1905
1906# ##Method
1907
1908# `GET`
1909
1910# ##URL Params
1911
1912# **None**
1913
1914# ##Data Params
1915
1916# * **name** : *string*, Email of the user
1917
1918# ##Success Response
1919
1920# * **Code:** 200
1921
1922# **Content:** `{ "foods": [
1923# {
1924# "food_catagories": "10",
1925# "name": "Biriani",
1926# "img_url": "http://img.url",
1927# "price": 70
1928# },
1929# {
1930# "food_catagories": "10",
1931# "name": "Kacchi Biriani",
1932# "img_url": "http://img.url",
1933# "price": 70
1934# },
1935# {
1936# "food_catagories": "10",
1937# "name": "Biriani",
1938# "img_url": "http://img.url",
1939# "price": 70
1940# }
1941# ] }`
1942
1943# ##Error Response
1944
1945# * **Code:** 404 NOT FOUND
1946
1947# **Content:** `{ 'message' : "You are already registerd. Is there any problem signing in??" }`
1948
1949# OR
1950
1951# * **Code:** 401 UNAUTHORIZED
1952
1953# **Content:** `{ error : "You are unauthorized to make this request." }`
1954
1955# ##Sample Call
1956
1957# ~~~~
1958
1959# curl -X GET intiaz-test.appspot.com/api/get_available_foods_list
1960# ~~~~
1961# """
1962# @auth.login_required
1963# def get(self):
1964# # foods = Food.query()
1965# # a = []
1966# # for f in foods:
1967# # a.append(f.to_dict())
1968# #return {'test': foods}
1969# #+++++++++++++++++++++ mysql database query +++++++++++++++++++
1970# """
1971# #food table definition
1972# CREATE TABLE foods (
1973# id INT NOT NULL AUTO_INCREMENT,
1974# name CHAR(100),
1975# category CHAR(100),
1976# price DECIMAL,
1977# image_url CHAR(100),
1978# PRIMARY KEY(id)
1979# ) ENGINE=INNODB;
1980
1981# """
1982# cnx = init_db()
1983# cursor = cnx.cursor(buffered=True)
1984# query = ("SELECT * FROM foods")
1985
1986# cursor.execute(query)
1987# app.logger.info('rows '+ str (cursor.stored_results()))
1988# a = []
1989# for row in cursor:
1990# a.append({
1991# 'id': row[0],
1992# 'name':row[1],
1993# # 'price': float(row[3]),
1994# 'image_url': row[3]
1995# })
1996# # print("{}, {} was hired on {:%d %b %Y}".format(
1997# # last_name, first_name, hire_date))
1998
1999# try:
2000# cnx.commit()
2001# except:
2002# cnx.rollback()
2003# cursor.close()
2004
2005
2006# #+++++++++++++++++++++ mysql database query +++++++++++++++++++
2007# return {'foods': a}
2008
2009# api.add_resource(Get_available_foods_list, '/api/get_available_foods_list')
2010
2011class Get_food_suggestions(Resource):
2012 """
2013 #Get the list of foods
2014 ----
2015 This resource get the list of foods
2016
2017 ##URL
2018
2019 /api/get_available_foods_list
2020
2021 ##Method
2022
2023 `GET`
2024
2025 ##URL Params
2026
2027 **None**
2028
2029 ##Data Params
2030
2031 * **name** : *string*, Email of the user
2032
2033 ##Success Response
2034
2035 * **Code:** 200
2036
2037 **Content:** `{ "foods": [
2038 {
2039 "food_catagories": "10",
2040 "name": "Biriani",
2041 "img_url": "http://img.url",
2042 "price": 70
2043 },
2044 {
2045 "food_catagories": "10",
2046 "name": "Kacchi Biriani",
2047 "img_url": "http://img.url",
2048 "price": 70
2049 },
2050 {
2051 "food_catagories": "10",
2052 "name": "Biriani",
2053 "img_url": "http://img.url",
2054 "price": 70
2055 }
2056 ] }`
2057
2058 ##Error Response
2059
2060 * **Code:** 404 NOT FOUND
2061
2062 **Content:** `{ 'message' : "You are already registerd. Is there any problem signing in??" }`
2063
2064 OR
2065
2066 * **Code:** 401 UNAUTHORIZED
2067
2068 **Content:** `{ error : "You are unauthorized to make this request." }`
2069
2070 ##Sample Call
2071
2072 ~~~~
2073
2074 curl -X GET intiaz-test.appspot.com/api/get_available_foods_list
2075 ~~~~
2076 """
2077 # @auth.login_required
2078 def get(self):
2079 # foods = Food.query(Food.name == foodname)
2080 # a = []
2081 # for f in foods:
2082 # a.append(f.to_dict())
2083 #return {'test': foods}
2084
2085 parser = reqparse.RequestParser()
2086 parser.add_argument('name', type=str, help='Enter Food Name', required=True)
2087 args = parser.parse_args()
2088
2089 cnx = init_db()
2090 cursor = cnx.cursor(buffered=True)
2091 query = ("SELECT * FROM foods where name like %s")
2092
2093 cursor.execute(query, ("%" + args['name'] + "%",))
2094 a = []
2095 for row in cursor:
2096 a.append({
2097 'name':row[1],
2098 'id': row[0],
2099 'image_url': row[3]
2100 })
2101 # print("{}, {} was hired on {:%d %b %Y}".format(
2102 # last_name, first_name, hire_date))
2103
2104 try:
2105 cnx.commit()
2106 except:
2107 cnx.rollback()
2108 cursor.close()
2109
2110
2111 #+++++++++++++++++++++ mysql database query +++++++++++++++++++
2112 return {'foods': a}
2113
2114api.add_resource(Get_food_suggestions, '/api/get_food_suggestions')
2115
2116# class Add_new_order(Resource):
2117# """
2118# #Add an order
2119# ----
2120# This resource add an order
2121# This resource let the waiter to take an order
2122
2123# ##URL
2124
2125# /api/add_new_order
2126
2127# ##Method
2128
2129# `POST`
2130
2131# ##URL Params
2132
2133# **None**
2134
2135# ##Data Params
2136
2137# * **restaurant_id** : *string*, Email of the user
2138# * **customer_id** : *string*, Email of the user
2139# * **cook_id** : *string*, Email of the user
2140# * **table_no** : *string*, Email of the user
2141# * **food_list** : *string*, Email of the user
2142
2143# ##Success Response
2144
2145# * **Code:** 200
2146
2147# **Content:** `{ 'message': 'You have been registerd successfully' }`
2148
2149# ##Error Response
2150
2151# * **Code:** 404 NOT FOUND
2152
2153# **Content:** `{ 'message' : "You are already registerd. Is there any problem signing in??" }`
2154
2155# OR
2156
2157# * **Code:** 401 UNAUTHORIZED
2158
2159# **Content:** `{ error : "You are unauthorized to make this request." }`
2160
2161# ##Sample Call
2162
2163# ~~~~
2164
2165# curl -X POST intiaz-test.appspot.com/api/add_new_order -d
2166# {
2167# 'restaurant_id':'5342114682503168'
2168# 'customer_id':'6244676289953792',
2169# 'cook_id':'5132107961597952',
2170# 'table_no':'10',
2171# 'food_list':{
2172# 'food1':'1',
2173# 'food2':'2',
2174# 'food3':'3'
2175# }
2176# }
2177# ~~~~
2178# """
2179
2180# @auth.login_required
2181# def post(self):
2182# """
2183# food_list = ndb.JsonProperty()
2184# """
2185# try:
2186# # Parse the arguments
2187# parser = reqparse.RequestParser()
2188
2189# ## date_time = ndb.DateTimeProperty()
2190# ## restaurant_id = ndb.IntegerProperty()
2191# ## foods_id = ndb.StringProperty()
2192# ## quantity = ndb.IntegerProperty()
2193# ## customer_id = ndb.IntegerProperty()
2194# ## cook_id = ndb.IntegerProperty()
2195# ## table_no = ndb.IntegerProperty()
2196# ## order_status = ndb.IntegerProperty() #waiting, served, completed, canceled.
2197
2198# # parser.add_argument('date_time', type=str, help='Email address to create user')
2199# parser.add_argument('restaurant_id', type=int, help='Email address to create user')
2200# #parser.add_argument('foods_id', type=str, help='Password to create user')
2201# #parser.add_argument('quantity', type=int, help='Email address to create user')
2202# # parser.add_argument('customer_id', type=int, help='Email address to create user', required=True)
2203# parser.add_argument('table_no', type=int, help='Password to create user')
2204# # parser.add_argument('order_status', type=int, help='Email address to create user')
2205# parser.add_argument('ordered_foods', action='append', help='Add some foods')
2206# args = parser.parse_args()
2207# #return {'food':args['ordered_foods']}
2208
2209# # restaurant = Restaurant.get_by_id(args['restaurant_id'])
2210
2211# # customer_id = User.get_by_id(args['customer_id'])
2212
2213# # #Black box to calculate the best cook
2214# # employee_id =Employee.get_by_id(6258007868440576)
2215
2216# # order = Order(
2217# # restaurant_id=restaurant.key,
2218# # #quantity = args['quantity'],
2219# # customer_id=customer_id.key,
2220# # employee_id=employee_id.key,
2221# # table_no=args['table_no'],
2222# # order_status=1,
2223# # food_list={'food1':'1',
2224# # 'food2':'2',
2225# # 'food3':'3'})
2226
2227# # key = order.put()
2228# # r = key.get()
2229# #enque the order to the order list.
2230# """
2231# cur = mysql.connection.cursor()
2232# cur.execute('''SELECT user, host FROM mysql.user''')
2233# rv = cur.fetchall()
2234# return str(rv)
2235
2236# add_employee = ("INSERT INTO employees "
2237# "(first_name, last_name, hire_date, gender, birth_date) "
2238# "VALUES (%s, %s, %s, %s, %s)")
2239
2240# data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))
2241# cursor.execute(add_employee, data_employee)
2242# cnx.commit()
2243
2244
2245# add_employee = ("INSERT INTO employees "
2246# "(first_name, last_name, hire_date, gender, birth_date) "
2247# "VALUES (%s, %s, %s, %s, %s)")
2248# add_salary = ("INSERT INTO salaries "
2249# "(emp_no, salary, from_date, to_date) "
2250# "VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")
2251
2252# data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))
2253
2254# # Insert new employee
2255# cursor.execute(add_employee, data_employee)
2256# emp_no = cursor.lastrowid
2257
2258
2259# cursor.execute(add_salary, data_salary)
2260
2261# # Make sure data is committed to the database
2262# cnx.commit()
2263
2264# cursor.close()
2265
2266# CREATE TABLE orders (
2267# id INT NOT NULL AUTO_INCREMENT,
2268# restaurant_id INT NOT NULL,
2269# table_id INT NOT NULL,
2270# order_time_date DATETIME,
2271# order_submit BIT,
2272# order_processed BIT,
2273# order_checkedout BIT,
2274
2275# PRIMARY KEY(id),
2276# INDEX (restaurant_id),
2277
2278# FOREIGN KEY (restaurant_id)
2279# REFERENCES restaurant(id)
2280# ) ENGINE=INNODB;
2281
2282
2283# CREATE TABLE foods_of_orders (
2284# id INT NOT NULL AUTO_INCREMENT,
2285# order_id INT NOT NULL,
2286# food_id INT NOT NULL,
2287# special_comments CHAR(100),
2288
2289# PRIMARY KEY(id),
2290# INDEX (order_id, food_id),
2291
2292# FOREIGN KEY (order_id)
2293# REFERENCES orders(id),
2294
2295# FOREIGN KEY (food_id)
2296# REFERENCES foods(id)
2297# ) ENGINE=INNODB;
2298# """
2299# cnx = init_db()
2300# cursor = cnx.cursor()
2301# query = ("SELECT * FROM restaurant where id = %s")
2302# cursor.execute(query, (args['restaurant_id'],))
2303
2304# rv = cursor.fetchall()
2305# if(not len(rv)):
2306# return{'message':'error',
2307# 'description': 'No such restaurant'}
2308
2309# add_order = ("INSERT INTO orders "
2310# "(restaurant_id, table_id, order_time_date, order_submit, order_processed, order_checkedout)"
2311# "VALUES (%s, %s, %s, %s, %s, %s)")
2312# import time
2313# data_order = (args['restaurant_id'], args['table_no'],time.strftime('%Y-%m-%d %H:%M:%S'),True, True, True)
2314
2315# cursor.execute(add_order, data_order)
2316# order_no = cursor.lastrowid
2317
2318# cursor = cnx.cursor(buffered=True)
2319
2320# add_foods_of_order = ("INSERT INTO foods_of_orders "
2321# "(order_id, food_id, special_comments)"
2322# "VALUES (%s, %s, %s)")
2323# for food in args['ordered_foods']:
2324# #data = json.loads(food)['id']
2325# #return json.loads(food)['id']
2326# data_foods_of_order = (order_no, json.loads(food)['id'], 'No commnet')
2327# cursor.execute(add_foods_of_order, data_foods_of_order)
2328
2329# try:
2330# cnx.commit()
2331# except:
2332# cnx.rollback()
2333
2334# cursor.close()
2335# return {'id': order_no,
2336# 'status': 'success',
2337# 'description': 'Order has been added successfully'}
2338
2339# except Exception as e:
2340# return {'error': str(e)}
2341
2342
2343# api.add_resource(Add_new_order, '/api/add_new_order')
2344
2345def custom_list(value,name):
2346 return value;
2347
2348class order(Resource):
2349 def get(self, order_id=None):
2350 try:
2351 cnx = init_db()
2352 cursor = cnx.cursor()
2353 query = ("SELECT * FROM orders where id = %s")
2354 cursor.execute(query, (order_id,))
2355
2356 row = cursor.fetchone()
2357 try:
2358 cnx.commit()
2359 except:
2360 cnx.rollback()
2361 cursor.close()
2362
2363
2364 if(row is None):
2365 return{'error':'no such order'}
2366
2367 cursor = cnx.cursor()
2368 # aggregate information form multiple tables
2369 query = ("SELECT * FROM foods_of_orders left join restaurant_menu on restaurant_menu.id=foods_of_orders.menu_item_id left join foods on restaurant_menu.food_id=foods.id where foods_of_orders.order_id = %s")
2370 cursor.execute(query, (row[0],))
2371
2372 items=[]
2373
2374 for item_data in cursor:
2375 items.append({
2376 'item_id': item_data[0],
2377 'name': item_data[11],
2378 'price': item_data[8],
2379 'special_comment': item_data[4],
2380 'quantity': item_data[3]
2381 })
2382
2383
2384
2385 return {'order_id': row[0],
2386 'table_id':row[2],
2387 'order_time_date':str(row[3]),
2388 'order_submit':row[4],
2389 'order_processed':row[5],
2390 'order_checkedout':row[6],
2391 'status':row[7],
2392 'items': items
2393 }
2394
2395
2396 except Exception as e:
2397 return {'error': str(e)}
2398
2399
2400
2401
2402 def post(self, order_id=None):
2403 """
2404 restaurant id
2405 menu item id
2406 sample data format
2407
2408 restaurant_id:2
2409 table_id:1
2410 items:{"id":1,"id":2}
2411 special_comment:No comment
2412 """
2413 try:
2414 parser = reqparse.RequestParser()
2415
2416 parser.add_argument('restaurant_id', type=int, help='Email address to create user')
2417
2418 parser.add_argument('table_id', type=int, help='Password to create user')
2419
2420 parser.add_argument('items', type=custom_list, help='Add some foods')
2421
2422 parser.add_argument('status', type=str, help='add status')
2423
2424 args = parser.parse_args()
2425
2426 cnx = init_db()
2427 cursor = cnx.cursor()
2428
2429 #update order status
2430 if order_id is not None:
2431 app.logger.info('testing')
2432 query = ("UPDATE orders SET status=%s WHERE id=%s")
2433 cursor.execute(query, (args['status'],order_id))
2434 try:
2435 cnx.commit()
2436 except:
2437 cnx.rollback()
2438 cursor.close()
2439 return {"message":"success"}
2440
2441 #store data
2442 query = ("SELECT id FROM restaurant where id = %s")
2443 cursor.execute(query, (args['restaurant_id'],))
2444
2445 rv = cursor.fetchall()
2446 if(not len(rv)):
2447 return{'message':'error',
2448 'description': 'No such restaurant'}
2449
2450 add_order = ("INSERT INTO orders "
2451 "(restaurant_id, table_id, order_time_date, order_submit, order_processed, order_checkedout, status)"
2452 "VALUES (%s, %s, %s, %s, %s, %s, %s)")
2453 import time
2454 data_order = (args['restaurant_id'], args['table_id'],time.strftime('%Y-%m-%d %H:%M:%S'),1, 0, 0, 'waiting')
2455
2456 cursor.execute(add_order, data_order)
2457
2458 order_no = cursor.lastrowid
2459
2460 cursor = cnx.cursor(buffered=True)
2461
2462 add_foods_of_order = ("INSERT INTO foods_of_orders "
2463 "(order_id, menu_item_id, quantity, special_comments)"
2464 "VALUES (%s, %s, %s, %s)")
2465
2466 if(args['items'] is None):
2467 return {"error":"No food selected"}
2468
2469 # app.logger.info(json.loads(args['items']))
2470
2471 for food in json.loads(args['items']):
2472 # app.logger.info(food['id'])
2473 """
2474 id, quantity, special comment
2475 """
2476 data_foods_of_order = (order_no, food['menu_item_id'], food['quantity'], food['special_comments'])
2477 cursor.execute(add_foods_of_order, data_foods_of_order)
2478
2479 try:
2480 cnx.commit()
2481 except:
2482 cnx.rollback()
2483 cursor.close()
2484 return {'id': order_no,
2485 'status': 'success',
2486 'description': 'Order has been added successfully'}
2487
2488 except Exception as e:
2489 return {'error': str(e)}
2490
2491 def delete(self, order_id=None):
2492 """
2493 user should not allow to delete order data
2494 """
2495 pass
2496
2497api.add_resource(order, '/api/order', '/api/order/<int:order_id>')
2498
2499class table_list(Resource):
2500
2501 @auth.login_required
2502 def get(self):
2503 try:
2504 cnx = init_db()
2505 cursor = cnx.cursor()
2506 query = ("SELECT customer_capacity FROM restaurant where id = %s")
2507 cursor.execute(query, (g.rid,))
2508 ready = cursor.fetchone()
2509 ready = ready[0]
2510 # ready = 10
2511
2512
2513 cursor = cnx.cursor()
2514 query = ("SELECT id, table_id, status FROM orders WHERE restaurant_id = %s")
2515 cursor.execute(query, (g.rid,))
2516 # cursor.fetchall()
2517
2518
2519 # app.logger.info(cursor.fetchall())
2520 serving = []
2521 waiting = []
2522 checking_out=[]
2523 modified=[]
2524
2525 """
2526 {
2527 ready: 10,
2528 serving : [{table_id:5,order_id:12},{table_id:7,order_id:99}],
2529 waiting : [{table_id:2,order_id:543},{table_id:9,order_id:134}],
2530 checking_out : [{table_id:1,order_id:12}],
2531 modified : [{table_id:3,order_id:12}, {table_id:8,order_id:12}]
2532 }
2533 """
2534
2535 # rows = cursor.stored_results()
2536 # app.logger.info('rows '+ str (rows))
2537
2538
2539
2540 for row in cursor:
2541 # app.logger.info(row[4])
2542 # app.logger.info('woking..')
2543 status = row[2]
2544 if status=='serving':
2545 serving.append({
2546 'table_id': row[1],
2547 'order_id': row[0]
2548 })
2549 elif status=='waiting':
2550 waiting.append({
2551 'table_id': row[1],
2552 'order_id': row[0]
2553 })
2554 elif status == 'checkedOut':
2555 checking_out.append({
2556 'table_id': row[1],
2557 'order_id': row[0]
2558 })
2559 elif status == 'modified':
2560 modified.append({
2561 'table_id': row[1],
2562 'order_id': row[0]
2563 })
2564
2565 try:
2566 cnx.commit()
2567 except:
2568 cnx.rollback()
2569 cursor.close()
2570
2571 return{
2572 'ready': ready,
2573 'serving':serving,
2574 'waiting':waiting,
2575 'checking_out':checking_out,
2576 'modified':modified
2577 }
2578
2579 except Exception as e:
2580 return {'error': str(e)}
2581
2582
2583 def post(self):
2584 pass
2585
2586 def delete(self):
2587 pass
2588
2589api.add_resource(table_list, '/api/list_table')
2590
2591"""
2592clean table deprecated
2593
2594class Clean_table(Resource):
2595
2596 #Clean Table
2597 ----
2598 This resource submit a clean order to the task queue
2599 ##URL
2600
2601 /api/clean_table/<int:order_id>
2602
2603 ##Method
2604
2605 `POST`
2606
2607 ##URL Params
2608
2609 **order_id** : *int*, id of the order
2610
2611 ##Data Params
2612
2613 **None**
2614
2615 ##Success Response
2616
2617 * **Code:** 200
2618
2619 **Content:** `{'status': 'successful'}`
2620
2621 ##Error Response
2622
2623 * **Code:** 404 NOT FOUND
2624
2625 **Content:** `{ 'status': 'unsuccessful' }`
2626
2627 OR
2628
2629 * **Code:** 401 UNAUTHORIZED
2630
2631 **Content:** `{ error : "You are unauthorized to make this request." }`
2632
2633 ##Sample Call
2634
2635 ~~~~
2636
2637 curl -X GET intiaz-test.appspot.com/api/clean_table/62346333453
2638 ~~~~
2639
2640
2641 @auth.login_required
2642 def post(self, order_id):
2643 order = order_id
2644 if(order== 2):
2645 # order.order_status = 3
2646 # order.put()
2647 return {'status': 'successful'}
2648 else:
2649 return {'status': 'unsuccessful'}
2650api.add_resource(Clean_table, '/api/clean_table/<int:order_id>')
2651
2652"""
2653
2654# class Todays_foods_prediction(Resource):
2655# """
2656# #Get Food Prediction
2657# ----
2658# This resource provides predicted foods ids
2659
2660# ##URL
2661
2662# /api/todays_foods_prediction
2663
2664# ##Method
2665
2666# `GET`
2667
2668# ##URL Params
2669
2670# **None**
2671
2672# ##Data Params
2673
2674# **None**
2675
2676# ##Success Response
2677
2678# * **Code:** 200
2679
2680# **Content:** `{ 'message': 'You have been registerd successfully' }`
2681
2682# ##Error Response
2683
2684# * **Code:** 404 NOT FOUND
2685
2686# **Content:** `{ 'message' : "You are already registerd. Is there any problem signing in??" }`
2687
2688# OR
2689
2690# * **Code:** 401 UNAUTHORIZED
2691
2692# **Content:** `{ error : "You are unauthorized to make this request." }`
2693
2694# ##Sample Call
2695
2696# ~~~~
2697
2698# curl -X GET intiaz-test.appspot.com/api/todays_foods_prediction
2699# ~~~~
2700# """
2701# @auth.login_required
2702# def get(self):
2703
2704# # foods = Food.query()
2705# # a = []
2706# # for f in foods:
2707# # a.append(f.to_dict())
2708# return {'recomended_foods': {"sample":"food"}}
2709# api.add_resource(Todays_foods_prediction, '/api/todays_foods_prediction')
2710
2711
2712"""
2713
2714class Checkout(Resource):
2715
2716 #CheckOut
2717 ----
2718 This resource calculate final billing of an order and checkout
2719
2720 ##URL
2721
2722 /api/checkout/<int:order_id>'
2723
2724 ##Method
2725
2726 `POST`
2727
2728 ##URL Params
2729
2730 * **order_id** : *int*, The id of the order to be checkedout
2731
2732 ##Data Params
2733
2734 **None**
2735
2736 ##Success Response
2737
2738 * **Code:** 200
2739
2740 **Content:** `{ 'status': 'successful' }`
2741
2742 ##Error Response
2743
2744 * **Code:** 404 NOT FOUND
2745
2746 **Content:** `{ 'status': 'unsuccessful' }`
2747
2748 OR
2749
2750 * **Code:** 401 UNAUTHORIZED
2751
2752 **Content:** `{ error : "You are unauthorized to make this request." }`
2753
2754 ##Sample Call
2755
2756 ~~~~
2757
2758 curl -X POST intiaz-test.appspot.com/api/checkout/456416465564
2759 ~~~~
2760
2761 @auth.login_required
2762 def post(self, order_id):
2763 #get user
2764 #get restaurant
2765 #get table no
2766 #query table no with status == 1
2767 #get order by id
2768 #update status property
2769 #order = Order.query(Order.table_no==table_id AND Order.order_status==1)
2770 # order = Order.get_by_id(order_id)
2771 if(order.order_status == 2):
2772 order.order_status = 3
2773 # order.put()
2774 return {'status': 'successful'}
2775 else:
2776 return {'status': 'unsuccessful'}
2777api.add_resource(Checkout, '/api/checkout/<int:order_id>')
2778
2779"""
2780
2781# class Profit_maximization(Resource):
2782# pass
2783
2784# class Wish_list(Resource):
2785# """
2786# #Let the customer to add their wish food
2787# ----
2788# """
2789# pass
2790
2791
2792
2793
2794
2795class Dauthenticate_user(Resource):
2796 """
2797 #Deauthenticate user
2798 ----
2799 This resource logged the out.
2800
2801 ##URL
2802
2803 /api/signout
2804
2805 ##Method
2806
2807 `GET`
2808
2809 ##URL Params
2810
2811 **None**
2812
2813 ##Data Params
2814
2815 **None**
2816
2817 ##Success Response
2818
2819 * **Code:** 200
2820
2821 **Content:** `{ 'status': 'signedout' }`
2822
2823 ##Error Response
2824
2825 * **Code:** 401 UNAUTHORIZED
2826
2827 **Content:** `{ error : "You are unauthorized to make this request." }`
2828
2829 ##Sample Call
2830
2831 ~~~~
2832 curl -X GET intiaz-test.appspot.com/api/signout
2833 ~~~~
2834 """
2835 @auth.login_required
2836 def get(self):
2837 #g.user.invalidate()
2838 cnx = init_db()
2839 cursor = cnx.cursor()
2840 add_auth_user = ("UPDATE user SET nonce='' WHERE id= %s")
2841 data_auth_user = (g.uid,)
2842 cursor.execute(add_auth_user, data_auth_user)
2843 try:
2844 cnx.commit()
2845 except:
2846 cnx.rollback()
2847 cursor.close()
2848 # g.user.nonce = ''
2849 # g.user.put()
2850 return {'status': 'signedout'}
2851api.add_resource(Dauthenticate_user, '/api/signout')
2852
2853
2854
2855
2856
2857
2858
2859
2860class Reviews(Resource):
2861
2862 def post(self):
2863
2864 parser = reqparse.RequestParser()
2865 parser.add_argument('restaurant_id', type=int, help='Please mention a place')
2866 parser.add_argument('environment', type=int, help='How was environment')
2867 parser.add_argument('behavior', type=int, help='How was environment')
2868 parser.add_argument('review_comment', type=str, help='How was environment')
2869 parser.add_argument('waiting_time', type=int, help='How was environment')
2870 parser.add_argument('items', type=custom_list, help='Please mention food items')
2871
2872 args = parser.parse_args()
2873
2874 # app.logger.info(args)
2875
2876 """
2877 id INT NOT NULL AUTO_INCREMENT,
2878 restaurant_id INT NOT NULL,
2879 environment INT NOT NULL,
2880 behavior INT NOT NULL,
2881 review_comment CHAR(100),
2882 waiting_time TIME,
2883
2884 review_id INT NOT NULL,
2885 food_id INT NOT NULL,
2886 food_price INT NOT NULL,
2887 food_comment INT NOT NULL,
2888 food_score INT NOT NULL,
2889 """
2890 cnx = init_db()
2891 cursor = cnx.cursor()
2892 query = ("INSERT INTO reviews "
2893 "(restaurant_id, environment, behavior, review_comment, waiting_time)"
2894 "VALUES (%s, %s, %s, %s, %s)")
2895 # app.logger.info(args['restaurant_id'])
2896 data = (args['restaurant_id'],args['environment'],args['behavior'],args['review_comment'],args['waiting_time'])
2897 cursor.execute(query, data)
2898
2899 #getting review id
2900 review_id = cursor.lastrowid
2901 #reinitializing cursor id
2902 cursor = cnx.cursor(buffered=True)
2903 #review items insert query
2904 query = ("INSERT INTO review_items "
2905 "(review_id, food_id, food_price, food_comment, food_score)"
2906 "VALUES (%s, %s, %s, %s, %s)")
2907
2908 # app.logger.info(args['items'])
2909 #iterating over the items
2910 for food in json.loads(args['items']):
2911 # app.logger.info(food['food_id'])
2912 data = (review_id, food['food_id'], food['food_price'], food['food_comment'],food['food_score'])
2913 cursor.execute(query, data)
2914
2915 try:
2916 cnx.commit()
2917 except:
2918 cnx.rollback()
2919 return{'id':review_id}
2920
2921api.add_resource(Reviews, '/api/review')
2922
2923
2924
2925
2926
2927
2928
2929app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
2930
2931
2932if __name__ == '__main__':
2933 # app.run(debug=True, host='0.0.0.0')
2934 app.run(debug=True, host='127.0.0.1',threaded=True)