Ejemplo n.º 1
0
class ZomotoAPI:
    def __init__(self):

        # Api secret keys stored in enviornment variable

        self.api_key = os.environ.get('api_key')

    def get_Categories(self, citi_id):

        self.api_client_auth = Pyzomato(self.api_key)

        self.api_client_auth.search(name="Chennai")

        # city id for chennai is 7

        return self.api_client_auth.getCategories()

    def search_city_by_geo_code(self, latitude, longitude):

        return self.api_client_auth.getByGeocode(latitude, longitude)

    def locating_res_by_id(self, res_id):

        # id > 18387708
        # name > kakada ramprasad
        # "locality_verbose": "Kilpauk, Chennai"

        return self.api_client_auth.getRestaurantDetails(res_id)
Ejemplo n.º 2
0
def search(request):
	p = Pyzomato('')
	list = []
	try:
		searchCategory = request.GET.get('searchCategory','')
		searchKeyWord = request.GET.get('searchKeyWord','')
		response=''
		if searchCategory == 'cuisines':
			cuisine_id = ''
			cusineResponse = p.getCuisines(city_id = '4')
			for num, cuisine in enumerate(cusineResponse['cuisines']):
				if cuisine['cuisine']['cuisine_name'] == searchKeyWord:
					cuisine_id = cuisine['cuisine']['cuisine_id']
			response = p.search(entity_type="city", entity_id='4',cuisines=cuisine_id)
		if searchCategory == 'restaurantType':
			restaurantTypeValue = ''
			restaurantTypeResponse = p.getEstablishments(city_id = '4')
			for num, establishment in enumerate(restaurantTypeResponse['establishments']):
				if establishment['establishment']['name'] == searchKeyWord:
					restaurantTypeValue = establishment['establishment']['id']
			response = p.search(entity_type="city", entity_id='4', establishment_type=restaurantTypeValue)
		if searchCategory == 'restaurantCategory':
			category_id = ''
			category_response = p.getCategories()
			for num, category in enumerate(category_response['categories']):
				if category['categories']['name'] == searchKeyWord:
					category_id = category['categories']['id']
			response = p.search(entity_type="city", entity_id='4', category=category_id)
	except Exception as e:
		print(e)
	try:
		for num, restaurant in enumerate(response['restaurants']):
			number= num+1,
			name=restaurant['restaurant']['name']
			name = name.format()
			url=restaurant['restaurant']['url']
			cuisines=restaurant['restaurant']['cuisines']
			rating=restaurant['restaurant']['user_rating']['aggregate_rating']
			icon=restaurant['restaurant']['thumb']
			price=restaurant['restaurant']['average_cost_for_two']
			res_id=restaurant['restaurant']['id']
			dictlist = [dict() for x in range(9)]
			dictlist={'number':number, 'name':name, 'url':url, 'cuisines':cuisines, 'rating':rating, 'icon':icon, 'price':price, 'res_id':res_id }
			list.append(dictlist)
	except Exception as e:
		print(e)
	return render(request, 'home.html', {'context': list})
Ejemplo n.º 3
0
def getZomato(request):
    p = Pyzomato('1c9999881f4fe458a246ecbb5e5a4f36')
    if request.method == 'POST':
        zomato_form = ZomatoForm(request.POST)
        if zomato_form.is_valid():
            data2 = zomato_form.cleaned_data
            resp2 = p.search(q=data2['locationcity'],
                             lat='41.277072',
                             lon='-96.060682',
                             radius='25000',
                             count='3',
                             sort='rating')
    return HttpResponse(json.dumps(resp2))
Ejemplo n.º 4
0
class tomatoes(object): 
    def __init__(self): 

        self.conn = sqlite3.connect('project.db')
        c = self.conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS restaurant (restaurant_name, restaurant_location)''')
        c.execute('''CREATE TABLE IF NOT EXISTS photos (restaurant_name, img_link, user)''')
        self.conn.commit()
        #zomato key
      
        self.p = Pyzomato("4fec777b3693765001b7f8000cfd2da8")

        rest_to_add = 20

        c = self.conn.cursor()
        for row in c.execute('SELECT * FROM city_hourly'):
            latitude= row[0].split(",")[1]
            langtitude= row[0].split(",")[0]

            restaurants = self.p.search(lat=latitude, lon=langtitude)["restaurants"]
            for restaurant in restaurants:
                if rest_to_add > 0:
                    name = restaurant["restaurant"]["name"]
                    location = restaurant["restaurant"]["location"]["address"]
                    c.execute('INSERT INTO restaurant VALUES (?,?)', (name ,location,))
                    self.conn.commit()
                    rest_to_add -= 1
                else:
                    return

                if "photos" in restaurant["restaurant"]: 
                    for review in restaurant["restaurant"]["photos"]:
                        name = restaurant["restaurant"]["name"]
                        user = review["photo"]["user"]["name"]
                        img = review["photo"]["url"]
                        if rest_to_add > 0:
                            c.execute('INSERT INTO photos VALUES (?,?,?)', (name, img, user))
                            self.conn.commit()
                            rest_to_add -= 1
                        else:
                            return
Ejemplo n.º 5
0
def searchRestaurant(request):
    p = Pyzomato('c5515b949415a90fe3c9dfebf2d1b246')
    if request.GET.get('city', False) or request.GET.get('search', False):
        city = request.GET["city"]
        search_key = request.GET["search"]

        city = p.getLocations("query=" + str(city))
        res_id = []
        data = {}

        search_results = p.search(
            entity_id=city['location_suggestions'][0]['entity_id'],
            entity_type=city['location_suggestions'][0]['entity_type'],
            q=search_key)
        # print(search_results['restaurants'][0]['restaurant']['R']['res_id'],search_results['restaurants'][1]['restaurant']['R']['res_id'])
        # search_results = p.search(entity_id=city['location_suggestions'][id]['entity_id'], entity_type=city['location_suggestions'][id]['entity_type'] ,q=search_key)
        try:
            for id in range(0, 10):
                resta_id = search_results['restaurants'][id]['restaurant'][
                    'R']['res_id']
                data[resta_id] = {}
                data[resta_id]['name'] = search_results['restaurants'][id][
                    'restaurant']['name']
                data[resta_id]['cusine'] = search_results['restaurants'][id][
                    'restaurant']['cuisines']
                data[resta_id]['address'] = search_results['restaurants'][id][
                    'restaurant']['location']['address']
                data[resta_id]['average_cost_for_two'] = search_results[
                    'restaurants'][id]['restaurant']['average_cost_for_two']
                data[resta_id]['rating'] = search_results['restaurants'][id][
                    'restaurant']['user_rating']['aggregate_rating']
                res_id.append(resta_id)
        except:
            status = 'failed'
        else:
            status = 'success'
        if status == 'success':
            return render(
                request, 'Restaurant_Search/SearchResults.html', {
                    'res_id': res_id,
                    'data': data,
                    'city': request.GET["city"],
                    'search_key': search_key
                })
        if status == 'failed':
            return render(
                request, 'Restaurant_Search/SearchResults.html', {
                    'res_id': res_id,
                    'data': data,
                    'city': request.GET["city"],
                    'search_key': search_key,
                    'no_results': 'no_results'
                })

    elif request.GET.get('res_id', False):
        res_id = request.GET["res_id"]
        data = p.getRestaurantDetails(restaurant_id=res_id)

        print(data['name'])
        data
        return JsonResponse(data)
Ejemplo n.º 6
0
@author: sameerkumar
"""

from pyzomato import Pyzomato
import os

fileExists = os.path.isfile('zomatoData.txt')
headerList = [
    'restaurant_id', 'rating', 'review_id', 'review_text', 'rating_color',
    'review_time_friendly', 'rating_text', 'time_stamp', 'likes',
    'comment_count', 'user_name', 'user_zomatohandle', 'user_foodie_level',
    'user_level_num', 'foodie_color', 'profile_url', 'profile_image'
]
restaurantIdList = []
p = Pyzomato("a6bbe2d54ec7dd7741ef5991f9a9cafa")
results = p.search(lat="33.222063", lon="-96.972784")
restaurants = results['restaurants']
for restaurant in restaurants:
    restaurantId = 0
    restaurantId = restaurant['restaurant']['R']['res_id']
    restaurantIdList.append(restaurantId)

for restaurantId in restaurantIdList:
    reviews = p.getRestaurantReviews(restaurantId)
    userReviews = reviews['user_reviews']
    for review in userReviews:
        reviewContentList = []
        userReview = review['review']
        rating = userReview['rating']
        reviewId = userReview['id']
        reviewText = userReview['review_text'].encode('utf-8').strip()
#Oleksandr Bihary
#Using Zomato API we obtain resturants names in the Las Vegas area and their Reviews
#API KEY: aa2e170fced5e4de42b96789a76fbd7f

import pprint
from pyzomato import Pyzomato
pp = pprint.PrettyPrinter(indent=2)

p = Pyzomato("aa2e170fced5e4de42b96789a76fbd7f")
p.search(q="las vegas")

categories = p.getCategories()
pp.pprint( categories )

dets = p.getCollectionsViaCityId(282)
pp.pprint( dets )

cus = p.getCuisines(282)
pp.pprint( cus )

estab = p.getEstablishments(282)
pp.pprint( estab )

#need resturant ID
menu = p.getDailyMenu(292)
pp.pprint( menu )

#need resturant ID
info = p.getRestaurantDetails(292)
pp.pprint( info )
Ejemplo n.º 8
0
class Ui_GroupBox(object):
    def setupUi(self, GroupBox):
        GroupBox.setObjectName("GroupBox")
        GroupBox.resize(434, 435)
        GroupBox.setStyleSheet(
            "QGroupBox { background-color: rgb(100, 255,255); border:1px solid rgb(255, 170, 255); }"
        )

        # ADD GRIDS
        self.gridLayout_9 = QtGui.QGridLayout(GroupBox)
        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout_2 = QtGui.QGridLayout()
        self.gridLayout_3 = QtGui.QGridLayout()
        self.gridLayout_4 = QtGui.QGridLayout()
        self.gridLayout_5 = QtGui.QGridLayout()
        self.gridLayout_6 = QtGui.QGridLayout()
        self.gridLayout_7 = QtGui.QGridLayout()
        self.gridLayout_8 = QtGui.QGridLayout()

        # ADD THE GRID TO THE LAYOUT USING ADDLAYOUT
        self.gridLayout.addLayout(self.gridLayout_6, 0, 0, 1, 1)
        self.gridLayout_9.addLayout(self.gridLayout, 0, 0, 1, 1)
        self.gridLayout.addLayout(self.gridLayout_7, 4, 0, 1, 1)
        self.gridLayout.addLayout(self.gridLayout_8, 3, 0, 1, 1)

        # SET ALL THE WIDGETS UNDER GROUPBOX
        self.label = QtGui.QLabel(GroupBox)
        self.label_2 = QtGui.QLabel(GroupBox)
        self.label_3 = QtGui.QLabel(GroupBox)
        self.pushButton = QtGui.QPushButton(GroupBox)
        self.lineEdit = QtGui.QLineEdit(GroupBox)
        self.lineEdit_2 = QtGui.QLineEdit(GroupBox)
        self.textEdit = QtGui.QTextEdit(GroupBox)

        # SET EXTRA PROPERTIES OF ALL WIDGETS NOW
        self.label.setTextFormat(QtCore.Qt.RichText)
        self.label.setAlignment(QtCore.Qt.AlignCenter)

        # SET TITLE AND TEXT OF THE WIDGETS
        self.setTitleText(GroupBox)

        # ADD THE WIDGETS TO THE GRIDLAYOUT
        self.gridLayout_6.addWidget(self.label, 0, 0, 1, 1)
        self.gridLayout_2.addWidget(self.label_2, 0, 0, 1, 1)
        self.gridLayout_3.addWidget(self.lineEdit, 0, 0, 1, 1)
        self.gridLayout_4.addWidget(self.label_3, 0, 0, 1, 1)
        self.gridLayout_5.addWidget(self.lineEdit_2, 0, 0, 1, 1)
        self.gridLayout_8.addWidget(self.pushButton, 0, 0, 1, 1)
        self.gridLayout_7.addWidget(self.textEdit, 0, 0, 1, 1)

        # SET THE HORIZONTAL LAYOUT
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout_2 = QtGui.QHBoxLayout()

        # ADD THE HORIZONTAL LAYOUT TO THE GRID
        self.horizontalLayout.addLayout(self.gridLayout_2)
        self.horizontalLayout.addLayout(self.gridLayout_3)
        self.horizontalLayout_2.addLayout(self.gridLayout_4)
        self.horizontalLayout_2.addLayout(self.gridLayout_5)

        # CLUB THE GRID TOGETHER AND ADD IT IN INSIDE THE HORIZONTAL LAYOUT USING ADDLAYOUT
        self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 1)
        self.gridLayout.addLayout(self.horizontalLayout_2, 2, 0, 1, 1)

        # MAKE ADDITIONAL LAYOUT PROPERTIES SIZEPOLICY,HOR/VERTICAL STRETCHES,MAXLENGTH,DRAGENABLE
        sizePolicy_label2 = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,
                                              QtGui.QSizePolicy.Expanding)
        sizePolicy_label2.setHorizontalStretch(0)
        sizePolicy_label2.setVerticalStretch(0)
        sizePolicy_label2.setHeightForWidth(
            self.label_2.sizePolicy().hasHeightForWidth())
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                                       QtGui.QSizePolicy.Expanding)
        sizePolicy_btn = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                                           QtGui.QSizePolicy.Fixed)

        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)

        # APPLY THE PROPERTIES TO THE WIDGETS
        sizePolicy.setHeightForWidth(
            self.lineEdit.sizePolicy().hasHeightForWidth())
        sizePolicy_btn.setHeightForWidth(
            self.pushButton.sizePolicy().hasHeightForWidth())
        sizePolicy.setHeightForWidth(
            self.lineEdit_2.sizePolicy().hasHeightForWidth())

        self.label_2.setSizePolicy(sizePolicy_label2)
        self.lineEdit.setSizePolicy(sizePolicy)
        self.lineEdit_2.setSizePolicy(sizePolicy)
        self.pushButton.setSizePolicy(sizePolicy_btn)

        self.lineEdit.setMaxLength(32791)
        self.lineEdit.setFrame(True)
        self.lineEdit.setDragEnabled(True)

        # SIGNALS AND EVENTS OF THE WIDGETS
        sig1 = QtCore.SIGNAL("textChanged(QString)")
        self.pushButton.clicked.connect(self.searchZomato)
        QtCore.QMetaObject.connectSlotsByName(GroupBox)

    def setTitleText(self, GroupBox):
        GroupBox.setWindowTitle("GroupBox")
        GroupBox.setTitle("GroupBox")
        self.label.setText(" MY ZOMATO APP")
        self.label_2.setText(" NAME OF THE CITY :-")
        self.label_3.setText(" NAME OF THE RESTAURANT/PUB :-")
        self.pushButton.setText("SUBMIT")

    def searchZomato(self):
        self.cityName = str(self.lineEdit.text())
        self.restName = str(self.lineEdit_2.text())
        self.mykey = '7dcf7b79d4c7bdfd5ffe013ae7361388'
        self.p = Pyzomato(self.mykey)
        print(dir(self.p))
        print('*' * 100)
        print('\n\n')
        print('INSIDE FUNCTION:-', inspect.stack()[0][3])
        print('CITY NAME AND RESTAURANT NAME\'S ARE "-', self.cityName,
              self.restName)
        print('THE ZOMATO API OBJECT:=', self.p)
        print('SEARCHING THE DATABASE FOR YOUR QUERY')
        print('\n\n')
        try:
            self.cityId = self.p.getCityDetails(q=self.cityName)
            l = self.cityId['location_suggestions']
            for d in l:
                for k, v in d.items():
                    if k == 'id':
                        self.cityId = d[k]
                        print('CITY ID:-', self.cityId)

            self.details = self.p.search(q=self.restName,
                                         city=self.cityName,
                                         count=10,
                                         entity_id=self.cityId,
                                         entity_type='city')
            print('\n\n THE DETAILS OF THE RESTAURANT ARE AS FOLLOWS:-',
                  self.details)
            self.output = zomato_script.searchRestaurant(
                self.details, self.restName.upper())
            self.processOutput(self.output)
        except Exception as exc:
            print('INVALID DETAILS ENTERED:-', exc)
            print('TRACEBACK :-', traceback.format_exc())

    def processOutput(self, output):
        f = open('zomato_rest_output.txt')
        a = f.read()
        self.textEdit.setText(a)
        f.close()
Ejemplo n.º 9
0
from pyzomato import Pyzomato
import json
import os
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.getenv('PROJECT_API_KEY')

p = Pyzomato(API_KEY)

# Create an empty list, that will be used to append each dictionary returned.
restaurantList = []

# Create a loop that iterates five times starting from 0th record and increases by increments of 20
for a in range(0, 100, 20):
    restaurants = p.search(lat=51.509865,
                           lon=-0.118092,
                           count=20,
                           sort='rating',
                           order='desc',
                           category=10,
                           start=a)
    print(a)
    restaurantList.append(restaurants)

# Write list of dictionaries to a json file
with open('Top60London.json', 'w') as fp:
    json.dump(restaurantList, fp)
Ejemplo n.º 10
0
                            flag=True
                            break

        if flag:
            print ('RESTAURANT DETAILS NOT FOUND... PLEASE ENTER THE CORRECT RESTAURANT NAME\n')


    f.close()






c=raw_input('PLEASE ENTER THE CITY TO WHICH YOUR RESTAURANT BELONGS:-\n\n')
r=raw_input('PLEASE ENTER THE NAME OF THE RESTAURANT WHICH YOU WANT TO LOOK FOR:-\n\n')
#c='bangalore'
#r="Ebony"
try:
   details=p.search(q=r,city=c,count=10)
   #print ('\n\n THE DETAILS OF THE RESTAURANT ARE AS FOLLOWS:-',details)
   searchRestaurant(details,r.upper())
except Exception as exc:
    print ('INVALID DETAILS ENTERED:-',exc)
    print ('TRACEBACK :-',traceback.format_exc())





Ejemplo n.º 11
0
from pyzomato import Pyzomato

p = Pyzomato(adb186fd589334b4ddda0aa4b2c8fc03)
p.search(q="london")

p.getCategories()