예제 #1
0
    def getEvents(sessionId, conditionals):
        '''
		Метод для запроса событий (по сессии и запросу)
		'''
        eventList = []
        userId = SessionManager.getUserId(sessionId)
        #TODO Обработка user-a;
        if userId > 0:
            latitudeR = conditionals['latitude']
            longitudeR = conditionals['longitude']
            radius = conditionals['radius']

            events = Event.objects.filter(
                PlaceId__latitude__range=(latitudeR - radius,
                                          latitudeR + radius),
                PlaceId__longitude__range=(longitudeR - radius,
                                           longitudeR + radius))
            #events =  Event.objects.filter()
            for event in events:
                addEvent = {}
                addEvent['id'] = event.pk
                addEvent['creatorId'] = event.creatorId
                addEvent['name'] = event.name
                addEvent['time'] = event.time
                addEvent['description'] = event.description
                addEvent['photo'] = event.photoId.photo
                addEvent['type'] = event.eventTypeId.name
                addEvent['latitude'] = event.PlaceId.latitude
                addEvent['longitude'] = event.PlaceId.longitude
                eventList.append(addEvent)
        return eventList
예제 #2
0
def main():
    search_url = "https://russian.alibaba.com/trade/search?fsb=y&IndexArea=product_en&SearchText="

    # Retrieve command line args
    pages = sys.argv[1].rstrip()
    search_str = ""
    if pages.isdigit():
        pages = int(pages)
        search_str = sys.argv[2].rstrip()
    else:
        pages = 2
        search_str = sys.argv[1].rstrip()

    merged_result = []
    sessionManager = SessionManager()

    search_url = search_url + parse.quote_plus(search_str) + '&page='
    # Iterate over pages
    for i in range(1, pages + 1):
        url = search_url + str(i)
        scrapper = PageScrapper(url)
        scrapper.sessionManager = sessionManager

        scrapper.get_page()
        scrapper.get_items()
        merged_result.append(scrapper.result)

    del sessionManager

    merged_result = [i for i in itertools.chain(*merged_result)]
    print(
        json.dumps(merged_result, indent=4, sort_keys=True,
                   ensure_ascii=False))
예제 #3
0
파일: userManager.py 프로젝트: bekas/MeToo
    def editAccount(userid, session_id, list_changes):
        """
		Метод для редактирования аккаунта
		"""
        userid2 = SessionManager.getUserId(session_id)
        if userid2 > 0:
            if userid == userid2:
                try:
                    u = models.User.objects.get(pk=userid)
                    u.avatarId = list_changes[0]
                    u.gender = list_changes[1]
                    u.description = list_changes[2]
                    u.save()

                    ui = models.UserInterest.objects
                    ui.filter(userId=iserid).delete()  # может не сработать
                    for interest in list_changes[3]:
                        new_ui = models.UserInterest(userId=userid, interestId=interest)
                        new_ui.save()

                    usn = models.UserSocialNetwork.objects
                    usn.filter(userId=iserid).delete()  # может не сработать
                    for network in list_changes[4]:
                        new_usn = models.UserSocialNetwork(userId=userid, socialNetworkId=network)
                        new_usn.save()

                    msg_code = 200
                except:
                    msg_code = -205
            else:
                msg_code = -204
        else:
            msg_code = -203
        return msg_code
예제 #4
0
파일: eventManager.py 프로젝트: bekas/MeToo
	def getEvents(sessionId, conditionals):
		'''
		Метод для запроса событий (по сессии и запросу)
		'''
		eventList = []
		userId = SessionManager.getUserId(sessionId)
		#TODO Обработка user-a;
		if userId > 0:
			latitudeR = conditionals['latitude']
			longitudeR = conditionals['longitude']
			radius = conditionals['radius']
		
			events =  Event.objects.filter(PlaceId__latitude__range=(latitudeR-radius,latitudeR+radius),PlaceId__longitude__range=(longitudeR-radius,longitudeR+radius))
			#events =  Event.objects.filter()
			for event in events:
				addEvent = {}			
				addEvent['id'] = event.pk
				addEvent['creatorId'] = event.creatorId
				addEvent['name'] = event.name
				addEvent['time'] = event.time
				addEvent['description'] = event.description
				addEvent['photo'] = event.photoId.photo
				addEvent['type'] = event.eventTypeId.name
				addEvent['latitude'] = event.PlaceId.latitude
				addEvent['longitude'] = event.PlaceId.longitude
				eventList.append(addEvent)
		return eventList
예제 #5
0
파일: tests.py 프로젝트: bekas/MeToo
    def test_get_sessionID(self):
        '''
		Метод начальной инициализации
		'''
        print "get"
        #fixtures = ['test_data.json','moar_data.json']
        sessionId = SessionManager.getSessionID(2)
        self.assertTrue(sessionId > 0)
예제 #6
0
파일: tests.py 프로젝트: bekas/MeToo
	def test_get_sessionID(self):
		'''
		Метод начальной инициализации
		'''
		print "get"
		#fixtures = ['test_data.json','moar_data.json'] 	
		sessionId = SessionManager.getSessionID(2);
		self.assertTrue(sessionId > 0)
예제 #7
0
def main(secondsAgo=None, year=None, exclude=None, reinit=False):
    manager = SessionManager()
    manager.generateEngine()
    manager.initializeDatabase(reinit)
    manager.createSession()

    loadFromTime = None
    startTime = datetime.now()
    if secondsAgo is not None:
        loadFromTime = startTime - timedelta(seconds=secondsAgo)
    if exclude != 'cce':
        loadCCE(manager, loadFromTime, year)
    if exclude != 'ccr':
        loadCCR(manager, loadFromTime, year)
    indexUpdates(manager, loadFromTime)

    manager.closeConnection()
예제 #8
0
    def createEvent(sessionId, eventArgs):
        '''
		Метод для создания событий (по сессии и списку аргументов)
		'''
        userId = SessionManager.getUser(sessionId)
        eName = 'Noname event'
        eTime = '2012-12-31'
        eDescription = 'No defenition'
        photo = Photo.objects.get(pk=1)
        eEventTypeId = 1
        eLatitude = 0
        eLongitude = 0
        eCountryId = Country.objects.get(pk=1)
        eCityId = City.objects.get(pk=1)
        eNamePlace = 'Noname place'

        if eventArgs.has_key('name'):
            eName = eventArgs['name']

        if eventArgs.has_key('time'):
            eTime = eventArgs['time']

        if eventArgs.has_key('description'):
            eDescription = eventArgs['description']

        if eventArgs.has_key('photo'):
            photo = Photo(photo=eventArgs['photo'])
            photo.save()
        else:
            photo = Photo.objects.get(pk=1)

        if eventArgs.has_key('eventTypeId'):
            eEventTypeId = eventArgs['eventTypeId']

        if eventArgs.has_key('longitude'):
            eLatitude = eventArgs['longitude']

        if eventArgs.has_key('latitude'):
            eLongitude = eventArgs['latitude']

        place = Place(cityId=eCityId,
                      countryId=eCountryId,
                      name=eNamePlace,
                      latitude=eLatitude,
                      longitude=eLongitude)
        place.save()
        newEvent = Event(creatorId=userId,
                         name=eName,
                         time=eTime,
                         description=eDescription,
                         photoId=photo,
                         eventTypeId_id=eEventTypeId,
                         PlaceId=place)
        newEvent.save()
        return newEvent.pk
예제 #9
0
	def modMeToo(sessionId,eventId,metooTypeId):
		'''
		Метод для измения типа похода
		'''
		userId = SessionManager.getUser(sessionId)
		if(userId != -1):
			metoo = MeToo.objects.get(userId=userId,eventId = eventId)
			metoo.metooTypeId = metooTypeId
			result = 500
		else:
			result = 501
		return result
예제 #10
0
	def delMeToo(sessionId,eventId):
		'''
		Метод отказа от события
		'''
		userId = SessionManager.getUser(sessionId)
		if(userId != -1):
			metoo = MeToo.objects.get(userId=userId,eventId = eventId)
			metoo.delete()
			result = 500
		else:
			result = 501
		return result
예제 #11
0
	def meToo(sessionId,eventId,metooTypeId):
		'''
		Метод, для того, чтобы пойти на событие
		'''
		userId = SessionManager.getUser(sessionId)
		if(userId != -1):
			metoo = MeToo(userId=userId,eventId = eventId, metooTypeId = metooTypeId)
			metoo.save()
			result = 500
		else:
			result = 501
		return result
예제 #12
0
파일: userManager.py 프로젝트: bekas/MeToo
    def disconnectUser(userid, session_id):
        """
		Метод для отключения пользователя от сервера
		"""
        userid2 = SessionManager.freeSessionID(session_id)  # заглушка для метода освобождения хэндла
        if userid2 > 0:
            if userid == userid2:  # и не надо мне говорить, что такого быть не может
                msg_code = userid2
            else:
                msg_code = -104
        else:
            msg_code = -105
        return msg_code  # возвращает айди юзера или код ошибки
예제 #13
0
파일: userManager.py 프로젝트: bekas/MeToo
    def disconnectUser(userid, session_id):
        '''
		Метод для отключения пользователя от сервера
		'''
        userid2 = SessionManager.freeSessionID(
            session_id)  #заглушка для метода освобождения хэндла
        if userid2 > 0:
            if userid == userid2:  # и не надо мне говорить, что такого быть не может
                msg_code = userid2
            else:
                msg_code = -104
        else:
            msg_code = -105
        return msg_code  # возвращает айди юзера или код ошибки
예제 #14
0
파일: eventManager.py 프로젝트: bekas/MeToo
	def deleteEvent(sessionId,eventId):
		'''
		Метод для удаления событий (по сессии и Id сессии)
		'''
		#TODO Удалять ли события?
		result = -1
		userId = SessionManager.getUser(sessionId)
		if EventManager.checkEvent(eventId):
			delEvent = Event.objects.get(pk=eventId)
			#delEvent.photo.delete()
			delEvent.delete()
			#TODO Вернуть норм ошибку
			result = 300
		return result
예제 #15
0
    def deleteEvent(sessionId, eventId):
        '''
		Метод для удаления событий (по сессии и Id сессии)
		'''
        #TODO Удалять ли события?
        result = -1
        userId = SessionManager.getUser(sessionId)
        if EventManager.checkEvent(eventId):
            delEvent = Event.objects.get(pk=eventId)
            #delEvent.photo.delete()
            delEvent.delete()
            #TODO Вернуть норм ошибку
            result = 300
        return result
예제 #16
0
파일: eventManager.py 프로젝트: bekas/MeToo
	def createEvent(sessionId,eventArgs):
		'''
		Метод для создания событий (по сессии и списку аргументов)
		'''
		userId = SessionManager.getUser(sessionId)
		eName = 'Noname event'
		eTime = '2012-12-31'
		eDescription = 'No defenition'
		photo = Photo.objects.get(pk = 1)
		eEventTypeId = 1
		eLatitude = 0
		eLongitude = 0
		eCountryId = Country.objects.get(pk = 1)
		eCityId = City.objects.get(pk = 1)
		eNamePlace = 'Noname place'
		
		if eventArgs.has_key('name'):
			eName = eventArgs['name']
			
		if eventArgs.has_key('time'):
			eTime = eventArgs['time']
			
		if eventArgs.has_key('description'):
			eDescription = eventArgs['description']
			
		if eventArgs.has_key('photo'):
			photo = Photo(photo = eventArgs['photo'])
			photo.save()
		else:
			photo = Photo.objects.get(pk = 1)
			
		if eventArgs.has_key('eventTypeId'):
			eEventTypeId = eventArgs['eventTypeId']
			
		if eventArgs.has_key('longitude'):
			eLatitude = eventArgs['longitude']
			
		if eventArgs.has_key('latitude'):
			eLongitude = eventArgs['latitude']	
		
		
		place = Place(cityId = eCityId, countryId = eCountryId, name = eNamePlace, latitude = eLatitude, longitude = eLongitude)
		place.save()
		newEvent = Event(creatorId = userId, name = eName, time = eTime, description = eDescription, photoId = photo, eventTypeId_id = eEventTypeId, PlaceId = place)
		newEvent.save()
		return newEvent.pk
예제 #17
0
파일: userManager.py 프로젝트: bekas/MeToo
    def connectUser(login, password):
        """
		Метод для подключения пользователя к серверу
		"""
        u = User.objects
        if u.filter(login__iexact=login, password__exact=password).exists():
            # не уверена, что в таком виде сожрет Оо
            userid = u.get(login__iexact=login, password__exact=password).pk
            session_id = SessionManager.getSessionID(userid)  # заглушка для метода выдачи хэндла
            if session_id > 0:
                msg_code = session_id
            else:
                msg_code = -103
        elif u.filter(login__iexact=login).exists():
            msg_code = -102
        else:
            msg_code = -101
        return msg_code  # возвращает айди сессии или код ошибки
예제 #18
0
    def modifyEvent(sessionId, eventId, eventArgs):
        '''
		Метод для редактирования событий (по сессии и списку аргументов)
		'''
        #TODO Обработка Юзера!
        userId = SessionManager.getUser(sessionId)
        modEvent = Event.objects.get(pk=eventId)

        #eName = modEvent.name
        #eTime = modEvent.time
        #eDescription = modEvent.description
        #photo = modEvent.photoId
        #eEventTypeId = modEvent.eventTypeId
        #place = modEvent.PlaceId
        #eLatitude = modEvent.PlaceId.latitude
        #eLongitude = modEvent.PlaceId.longitude
        #eCountryId = modEvent.PlaceId.countryId
        #eCityId = modEvent.PlaceId.cityId
        #eNamePlace = modEvent.PlaceId.name

        if eventArgs.has_key('name'):
            modEvent.name = eventArgs['name']
        if eventArgs.has_key('time'):
            modEvent.time = eventArgs['time']
        if eventArgs.has_key('description'):
            modEvent.description = eventArgs['description']

        #TODO: Подумать насчет изменений. Где они олжны происходить?
        if eventArgs.has_key('photo'):
            modEvent.photoId.photo = eventArgs['photo']
        if eventArgs.has_key('eventTypeId'):
            modEvent.eventTypeId_id = eventArgs['eventTypeId']
        if eventArgs.has_key('longitude'):
            modEvent.PlaceId.longitude = eventArgs['longitude']
        if eventArgs.has_key('latitude'):
            modEvent.PlaceId.latitude = eventArgs['latitude']

        modEvent.photoId.save()
        modEvent.eventTypeId.save()
        modEvent.PlaceId.save()
        modEvent.save()

        #TODO Обработка ошибок
        return modEvent.pk
예제 #19
0
파일: eventManager.py 프로젝트: bekas/MeToo
	def modifyEvent(sessionId,eventId,eventArgs):
		'''
		Метод для редактирования событий (по сессии и списку аргументов)
		'''
		#TODO Обработка Юзера!
		userId = SessionManager.getUser(sessionId)
		modEvent = Event.objects.get(pk=eventId)
		
		#eName = modEvent.name
		#eTime = modEvent.time
		#eDescription = modEvent.description
		#photo = modEvent.photoId
		#eEventTypeId = modEvent.eventTypeId
		#place = modEvent.PlaceId
		#eLatitude = modEvent.PlaceId.latitude
		#eLongitude = modEvent.PlaceId.longitude
		#eCountryId = modEvent.PlaceId.countryId
		#eCityId = modEvent.PlaceId.cityId
		#eNamePlace = modEvent.PlaceId.name
		
		if eventArgs.has_key('name'):
			modEvent.name = eventArgs['name']
		if eventArgs.has_key('time'):
			modEvent.time = eventArgs['time']
		if eventArgs.has_key('description'):
			modEvent.description = eventArgs['description']
		
		#TODO: Подумать насчет изменений. Где они олжны происходить?
		if eventArgs.has_key('photo'):
			modEvent.photoId.photo = eventArgs['photo']
		if eventArgs.has_key('eventTypeId'):
			modEvent.eventTypeId_id = eventArgs['eventTypeId']
		if eventArgs.has_key('longitude'):
			modEvent.PlaceId.longitude = eventArgs['longitude']
		if eventArgs.has_key('latitude'):
			modEvent.PlaceId.latitude = eventArgs['latitude']	
		
		modEvent.photoId.save()
		modEvent.eventTypeId.save()
		modEvent.PlaceId.save()
		modEvent.save()
		
		#TODO Обработка ошибок
		return modEvent.pk
예제 #20
0
파일: userManager.py 프로젝트: bekas/MeToo
    def connectUser(login, password):
        '''
		Метод для подключения пользователя к серверу
		'''
        u = User.objects
        if u.filter(login__iexact=login, password__exact=password).exists():
            # не уверена, что в таком виде сожрет Оо
            userid = u.get(login__iexact=login, password__exact=password).pk
            session_id = SessionManager.getSessionID(
                userid)  #заглушка для метода выдачи хэндла
            if session_id > 0:
                msg_code = session_id
            else:
                msg_code = -103
        elif u.filter(login__iexact=login).exists():
            msg_code = -102
        else:
            msg_code = -101
        return msg_code  # возвращает айди сессии или код ошибки
예제 #21
0
파일: userManager.py 프로젝트: bekas/MeToo
    def addFriends(userid, session_id, list_newfriends):  # !не проверяет правильность id друзей
        """
		Метод добавления друзей к пользователю
		"""
        userid2 = SessionManager.getUserId(session_id)
        if userid2 > 0:
            if userid == userid2:
                try:
                    f = models.Friend.objects.get(pk=userid)
                    friendline = f.friend
                    list_friends = list(set(friendline.split(";")) | set(list_newfriends))
                    friendline = ";".join(list_friends)

                    msg_code = 200
                except:
                    msg_code = -206
            else:
                msg_code = -204
        else:
            msg_code = -203
        return msg_code  # возвращает 200 или код ошибки
예제 #22
0
파일: userManager.py 프로젝트: bekas/MeToo
    def deleteFriends(userid, session_id, list_exfriends):
        """
		Метод удаления друзей у пользователя
		"""
        userid2 = SessionManager.getUserId(session_id)
        if userid2 > 0:
            if userid == userid2:
                try:
                    f = models.Friend.objects.get(pk=userid)
                    friendline = f.friend
                    list_friends = friendline.split(";")
                    list_friends = list(set(list_friends).difference(list_exfriends))
                    friendline = ";".join(list_friends)

                    msg_code = 200
                except:
                    msg_code = -206
            else:
                msg_code = -204
        else:
            msg_code = -203
        return msg_code  # возвращает 200 или код ошибки
예제 #23
0
파일: userManager.py 프로젝트: bekas/MeToo
    def getListFriends(userid, session_id):
        """
		Метод получения списка друзей
		"""
        userid2 = SessionManager.getUserId(session_id)
        if userid2 > 0:
            if userid == userid2:
                try:
                    f = models.Friend.objects.get(pk=userid)
                    friendline = f.friend
                    if friendline != "":
                        list_friends = friendline.split(";")
                    else:
                        list_friends = list()

                    msg_code = 200
                except:
                    msg_code = -207
            else:
                msg_code = -204
        else:
            msg_code = -203
        return msg_code, list_friends  # возвращает список id друзей, 200 или код ошибки
예제 #24
0
파일: userManager.py 프로젝트: bekas/MeToo
    def addFriends(userid, session_id,
                   list_newfriends):  # !не проверяет правильность id друзей
        '''
		Метод добавления друзей к пользователю
		'''
        userid2 = SessionManager.getUserId(session_id)
        if userid2 > 0:
            if userid == userid2:
                try:
                    f = models.Friend.objects.get(pk=userid)
                    friendline = f.friend
                    list_friends = list(
                        set(friendline.split(";")) | set(list_newfriends))
                    friendline = ";".join(list_friends)

                    msg_code = 200
                except:
                    msg_code = -206
            else:
                msg_code = -204
        else:
            msg_code = -203
        return msg_code  # возвращает 200 или код ошибки
예제 #25
0
	def getUsersbyEvent(sessionId,eventId):
		'''
		Метод, позволяющий узнать, кто идет на конкретное событие
		'''
		result = {}
		userId = SessionManager.getUser(sessionId)
		if(userId != -1):
			if(MeToo.objects.get(userId=userId,eventId = eventId).exist):
				metoo = MeToo.objects.filter(eventId = eventId)
				result['list'] = []
				for met in metoo:
					addUser = {}
					addUser['id'] = met.userId.pk
					addUser['login'] = met.userId.login
					addUser['avatar'] = met.userId.avatarId.photo
					addUser['rating'] = met.userId.rating
					result['list'].append(addUser)
				result['result'] = 500
			else:
				result['result'] = 502
		else:
			result['result'] = 501
		return result
예제 #26
0
파일: userManager.py 프로젝트: bekas/MeToo
    def deleteFriends(userid, session_id, list_exfriends):
        '''
		Метод удаления друзей у пользователя
		'''
        userid2 = SessionManager.getUserId(session_id)
        if userid2 > 0:
            if userid == userid2:
                try:
                    f = models.Friend.objects.get(pk=userid)
                    friendline = f.friend
                    list_friends = friendline.split(";")
                    list_friends = list(
                        set(list_friends).difference(list_exfriends))
                    friendline = ";".join(list_friends)

                    msg_code = 200
                except:
                    msg_code = -206
            else:
                msg_code = -204
        else:
            msg_code = -203
        return msg_code  # возвращает 200 или код ошибки
예제 #27
0
파일: userManager.py 프로젝트: bekas/MeToo
    def getListFriends(userid, session_id):
        '''
		Метод получения списка друзей
		'''
        userid2 = SessionManager.getUserId(session_id)
        if userid2 > 0:
            if userid == userid2:
                try:
                    f = models.Friend.objects.get(pk=userid)
                    friendline = f.friend
                    if friendline != '':
                        list_friends = friendline.split(";")
                    else:
                        list_friends = list()

                    msg_code = 200
                except:
                    msg_code = -207
            else:
                msg_code = -204
        else:
            msg_code = -203
        return msg_code, list_friends  # возвращает список id друзей, 200 или код ошибки
예제 #28
0
파일: userManager.py 프로젝트: bekas/MeToo
    def editAccount(userid, session_id, list_changes):
        '''
		Метод для редактирования аккаунта
		'''
        userid2 = SessionManager.getUserId(session_id)
        if userid2 > 0:
            if userid == userid2:
                try:
                    u = models.User.objects.get(pk=userid)
                    u.avatarId = list_changes[0]
                    u.gender = list_changes[1]
                    u.description = list_changes[2]
                    u.save()

                    ui = models.UserInterest.objects
                    ui.filter(userId=iserid).delete()  # может не сработать
                    for interest in list_changes[3]:
                        new_ui = models.UserInterest(userId=userid,
                                                     interestId=interest)
                        new_ui.save()

                    usn = models.UserSocialNetwork.objects
                    usn.filter(userId=iserid).delete()  # может не сработать
                    for network in list_changes[4]:
                        new_usn = models.UserSocialNetwork(
                            userId=userid, socialNetworkId=network)
                        new_usn.save()

                    msg_code = 200
                except:
                    msg_code = -205
            else:
                msg_code = -204
        else:
            msg_code = -203
        return msg_code
# Session config
app.config['SESSION_TYPE'] = 'mongodb'
app.config['SESSION_MONGODB'] = mongoClient
app.config['SESSION_MONGODB_DB'] = "citations-app2"
app.config['SESSION_MONGODB_COLLECT'] = "sessions"
app.config['SESSION_COOKIE_SECURE'] = True
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_PERMANENT'] = True
# For a 1 minute validity session, set minutes=121 (date is not the same format before database & this API)
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=122)
# if SESSION_USE_SIGNER set to True, you have to set flask.Flask.secret_key
app.config['SESSION_USE_SIGNER'] = True

Session(app)

sessMgr = SessionManager(mongo)
mailMgr = MailManager()
ph = PasswordHasher()
''' HEADERS
X-Frame-Options : 
    éviter les attaques de clickjacking pour s'assurer que le contenu ne soit pas embarqué dans d'autres sites
X-Content-Type-Options 
    est un marqueur utilisé par le serveur pour indiquer que les types MIME annoncés dans les en-têtes Content-Type ne doivent pas être modifiés ou et suivis  
'''
httpResponseHeaderOptions = {
    'X-Frame-Options': 'sameorigin',
    'X-Content-Type-Options': 'nosniff'
}


@app.route('/', methods=['GET', 'POST'])