def redirectByName(self, name): destination = None vapUrls = VapUrl.all() vapUrls.filter('name =', name) vapUrls.filter('vaporized =', False) vapUrls.filter('exp_datetime >=', datetime.datetime.now()) # can't use more than one inequality filter :( #vapUrls.filter('visits_remaining >', 0) if vapUrls.count() > 0: vapUrl = vapUrls[0] if vapUrl.visits_remaining > 0: destination = vapUrl.link vapUrl.visits_remaining -= 1 vapUrl.put() if destination == None: destination = '/' # we didn't go anywhere, so let's go home else: counters = Counter.all() counters.filter('type = ', 'visits/alltime') if counters.count() > 0: counter = counters[0] #TODO: make transactional counter.count += 1 counter.put() else: counter = Counter() counter.type = 'visits/alltime' counter.count = 1 counter.put() self.redirect(destination)
def create(self, url, max_time, max_visits): """Creates a new VapUrl and returns it if successful""" random.seed(str(random.random()) + url) name = ''.join([random.choice('abcdefghijklmnopqrstuvwxyz-0123456789') for i in range(10)]) vapUrl = None try: vapUrl = VapUrl() vapUrl.name = name vapUrl.link = db.Link(url) vapUrl.vaporized = False vapUrl.exp_datetime = datetime.datetime.now() + datetime.timedelta(minutes=max_time) vapUrl.visits_max = max_visits vapUrl.visits_remaining = max_visits vapUrl.put() except: vapUrl = None if vapUrl != None: counters = Counter.all() counters.filter('type = ', 'creates/alltime') if counters.count() > 0: counter = counters[0] #TODO: make transactional counter.count += 1 counter.put() else: counter = Counter() counter.type = 'creates/alltime' counter.count = 1 counter.put() return vapUrl;
def count(): try: counter = Counter.query(Counter.name == 'hello').fetch()[0] except IndexError: log.info('New counter.') counter = Counter(name='hello', count=0) counter.count += 1 counter.put() return
def get_current_counter(user: User) -> Counter: sql_check = """ SELECT counter_id, name, value FROM counter WHERE counter_id IN (SELECT cur_counter_id FROM "user" WHERE "user".user_id=%s); """ conn = None try: conn = psycopg2.connect(AUTH_STRING) cur = conn.cursor() cur.execute(sql_check, (user.user_id,)) row = cur.fetchone() return Counter(row[0], row[1], user, row[2]) except (Exception, psycopg2.DatabaseError) as error: print('get_current_counter:', error) finally: if conn is not None: conn.close()
def add_counter_process(bot, update): user = User(update.effective_user.id, update.effective_user.username, STATUS.add_counter) txt = update.effective_message.text counter = Counter(None, txt, user) counter_dao.save_counter(counter) bot.send_message(chat_id=user.user_id, text="OK. Saved", parse_mode='HTML')
def get_counter(counter_id: str) -> Counter: sql_check = """ SELECT u.user_id, u.username, u.status, counter_id, name, value FROM counter INNER JOIN "user" u on counter.user_id = u.user_id WHERE counter_id=%s; """ conn = None out = None try: conn = psycopg2.connect(AUTH_STRING) cur = conn.cursor() cur.execute(sql_check, (counter_id,)) res = cur.fetchone() if res is not None: user = User(res[0], res[1], res[2]) out = Counter(res[3], res[4], user, res[5]) return out except (Exception, psycopg2.DatabaseError) as error: print('get_counter:', error) finally: if conn is not None: conn.close()
def test_force_update(self): c = Counter.objects.create(name="one", value=1) # The normal case c.value = 2 c.save() # Same thing, via an update c.value = 3 c.save(force_update=True) # Won't work because force_update and force_insert are mutually # exclusive c.value = 4 self.assertRaises(ValueError, c.save, force_insert=True, force_update=True) # Try to update something that doesn't have a primary key in the first # place. c1 = Counter(name="two", value=2) self.assertRaises(ValueError, c1.save, force_update=True) c1.save(force_insert=True) # Won't work because we can't insert a pk of the same value. sid = transaction.savepoint() c.value = 5 self.assertRaises(IntegrityError, c.save, force_insert=True) transaction.savepoint_rollback(sid) # Trying to update should still fail, even with manual primary keys, if # the data isn't in the database already. obj = WithCustomPK(name=1, value=1) self.assertRaises(DatabaseError, obj.save, force_update=True)
def counter(request): contador = Counter.objects.all() #Condiciones para el contador local #si en el array de sesion ya exite la variable 'countSession' sumamos uno al contador if "countSession" in request.session: request.session["countSession"] += 1 #si en el array de sesion no exite la variable 'countSession', la creamos e inicializamos a 1 else: request.session["countSession"] = 1 #Condiciones para el contador global #si exite alguna tabla contador if contador.exists(): #Sumamos uno a la variable 'countGlobal' y guardamos la modificacion contador = contador[0] contador.countGlobal += 1 contador.save() else: #Inicializamos la Tabla contador con la variable 'countGlobal' a 1 contador = Counter(countGlobal=1) contador.save() #Mostramos la pagina counter.html pasandole la informacion actualizada de los contadores return render( request, 'server/counter.html', { 'counterSes': request.session["countSession"], 'counterGlobal': contador.countGlobal })
def get_user_counters(user: User) -> List[Counter]: sql_check = """ SELECT counter_id, name, value FROM counter WHERE user_id=%s; """ conn = None out = [] try: conn = psycopg2.connect(AUTH_STRING) cur = conn.cursor() cur.execute(sql_check, (user.user_id,)) while True: res = cur.fetchmany(100) if not res: break else: for row in res: out.append(Counter(row[0], row[1], user, row[2])) return out except (Exception, psycopg2.DatabaseError) as error: print('get_counter:', error) finally: if conn is not None: conn.close()
def test_update_with_no_pk(self): # Try to update something that doesn't have a primary key in # the first place. c1 = Counter(name="two", value=2) self.assertRaises(ValueError, c1.save, force_update=True) c1.save(force_insert=True)
def count_words_at_url(url): resp = requests.get(url) word_count = len(resp.text.split()) try: instance = Counter(url=url, word_count=word_count) db.session.add(instance) db.session.commit() return instance.id except: print('not able to insert in db')
def get(self): self.tv['page'] = 'statistics' counter = None self.tv['data'] = None counter_id = self.request.get('counter_id') if counter_id: counter = Counter.get_by_id(counter_id) # just get latest count if not counter: counter = Counter.query().order(-Counter.created).get() if counter: self.tv['data'] = counter.data.copy() else: self.tv['data'] = {} self.render()
def hello(): msg = request.get_cookie('msg', secret=secret) if msg is None: log.info('Api request without sid.') taskqueue.add(url='/tasks/count') try: counter = Counter.query(Counter.name == 'hello').fetch()[0] count = counter.count except IndexError: count = 0 return '%s - %s' % (msg, str(count)) return str(counter)
def get(self): try: is_dev = os.environ['SERVER_SOFTWARE'].startswith('Dev') except: is_dev = False path = os.path.join(os.path.dirname(__file__), 'templates', 'monitor.html') template_values = {} template_values['users'] = {} users_counter = Counter.get_by_key_name('users') if users_counter is None: template_values['users']['count'] = 1 else: template_values['users']['count'] = users_counter.count self.response.out.write(template.render(path, template_values))
def main_page(request): """главная вьюха Arguments: - `request`: """ if request.method == 'POST': radioform = SetPassForm(request.POST) radioform.is_valid() num_passwords = int(radioform.cleaned_data['num_pass']) passwords = gen_passwords( os.path.dirname(__file__) + '/dicts/' + radioform.cleaned_data['language'], num=num_passwords, lenth=int(radioform.cleaned_data['lenth_pass']), upper=radioform.cleaned_data['upper_pass'], numbers=radioform.cleaned_data['string_replace_num']) else: passwords = gen_passwords(os.path.dirname(__file__) + '/dicts/italian') num_passwords = 10 radioform = SetPassForm({ 'num_pass': '******', 'lenth_pass': '******', 'language': 'italian', 'upper_pass': True, 'string_replace_num': True }) count = Counter() log = Log() counter = count.get_counter(num_passwords) log.save_log_note(request.META['HTTP_USER_AGENT'], request.META['REMOTE_ADDR']) return render_to_response('index.html', { 'counter': counter, 'passwords': passwords, 'radioform': radioform, 'browser': request.META['HTTP_USER_AGENT'], 'ip': request.META['REMOTE_ADDR'] }, context_instance=RequestContext(request))
def run_counter(counter_id=None, cursor_urlsafe=None, set_classification_flags=False): if not counter_id: counter_id = generate_counter_id() counter_instance = Counter(id=counter_id) counters_data = {} else: counter_instance = Counter.get_by_id(counter_id) counters_data = counter_instance.data n = 50 query = APIData.query() query = query.filter(APIData.archived == False) environment_key = ndb.Key('Environment', 'PUBLIC') query = query.filter(APIData.environment == environment_key) tag = create_indexed_tag('type', 'PROJECT') query = query.filter(APIData.indexed_data == tag) query = query.order(APIData._key) if cursor_urlsafe: curs = Cursor(urlsafe=cursor_urlsafe) projects, cursor, more = query.fetch_page(n, start_cursor=curs) else: projects, cursor, more = query.fetch_page(n) new_projects = [] for project in projects: project_data = get_project_data(project) counters_data = increment_counts_with_province(counters_data, project_data) if set_classification_flags: if project_data['has_image']: project.indexed_data.append( create_indexed_tag('has_image', '1')) project.additional_data['has_image'] = '1' else: project.indexed_data.append( create_indexed_tag('has_image', '0')) project.additional_data['has_image'] = '0' if project_data['has_kml']: project.indexed_data.append(create_indexed_tag('has_kml', '1')) project.additional_data['has_kml'] = '1' else: project.indexed_data.append(create_indexed_tag('has_kml', '0')) project.additional_data['has_kml'] = '0' if project_data['has_classification']: project.indexed_data.append( create_indexed_tag('has_classification', '1')) project.additional_data['has_classification'] = '1' else: project.indexed_data.append( create_indexed_tag('has_classification', '0')) project.additional_data['has_classification'] = '0' project.indexed_data = uniquify(project.indexed_data) new_projects.append(project) counter_instance.data = counters_data if not cursor: counter_instance.done = True counter_instance.put() if set_classification_flags and new_projects: ndb.put_multi(new_projects) return { "counter_id": counter_id, "cursor": cursor.urlsafe() if cursor else None }