Esempio n. 1
0
def member_iteration(request,project_name,iteration,name):
    """
    This view returns the member-specific per iteration view, i.e mlapora's
    status for the Spoon iteration.
    """
    user_test = User.objects.filter(username=name)
    alias_test = Alias.objects.filter(alias=name)

    if user_test or alias_test:
        template = 'member_iter.html'
        
        #getting bug data
        b = bugsQuery.bugsQuery(project_name)
        c = b.getBugsForUserAndIteration(name,iteration)
        #getting task data
        d = sninjaQuery.sninjaQuery(project_name)

        if user_test:
            e = d.getTasksForUserAndIteration(user_test[0].email,iteration)
        else:
            e = d.getTasksForUserAndIteration(alias_test[0].email,iteration)
        
        context_data = {'member_name': name,'iteration':iteration, 'bugs': c, 'tasks':e, 'media_url':settings.MEDIA_URL}
        return render_to_response(template, context_data)
        
    else:   #modify the below to use users
        template= 'try_again-iteration.html'
        context_description = 'username'
        users = User.objects.all()
        all_choices = []
        for entry in users:
            all_choices.append(entry.username)
        context_data = {'bad_content':name, 'all_choices':all_choices, 'type':context_description, 'media_url':settings.MEDIA_URL}
        return render_to_response(template, context_data)    
Esempio n. 2
0
def iteration(request,project_name,iteration_name):
    """
    This view returns the iteration specific page, i.e. the Spoon iteration
    of RDS.
    """
    iterations = sninjaQuery.sninjaQuery(project_name).getStoryCollections
    name_test = Iteration.objects.filter(iteration=iteration_name)
    
    if name_test:
        #getting bug stats
        
        bugClass = bugsQuery.bugsQuery(project_name)
        bug_stats = bugClass.getBugNumbersForIteration(iteration_name)
        
        #getting task data
        taskClass = sninjaQuery.sninjaQuery(project_name)
        task_stats = taskClass.getUnclaimedTasksForIteration(iteration_name)
        
        template = 'iteration_dash.html'
        context_data = {'bugStats': bug_stats, 'iteration':iteration_name, 'taskStats':task_stats, 'media_url':settings.MEDIA_URL}
        return render_to_response(template, context_data)
    else:
        template= 'try_again-iteration.html'
        context_description = 'iteration'
        all_choices = []
        iterations = Iteration.objects.all()
        for entry in iterations:
            all_choices.append(entry.iteration)
        context_data = {'bad_content':iteration_name, 'all_choices':all_choices, 'type':context_description, 'media_url':settings.MEDIA_URL}
        return render_to_response(template, context_data)
Esempio n. 3
0
def process(request):

    if isLogged(request):
        return redirect('/stats/empire')

    if request.method == 'POST':
        lf = LoginForm(request.POST)
        if lf.is_valid():
            acc = Account.objects.get(login=lf.cleaned_data['login'])
            if acc.banexpire != None:
                if acc.banexpire < datetime.now():
                    acc.banexpire = None
                    acc.save()
                else:
                    return render_to_response('register/login/login.html', {'form':lf,
                                                                            'banned':True,
                                                                            'bannedto':acc.banexpire,
                                                                            'banreason':acc.banreason})
            sessLogin(acc, request)
            return redirect('/stats/empire/')
    try:
        lf
    except:
        lf = LoginForm()        
    
    return render_to_response('register/login/login.html', {'form':lf, 'banned':False})
Esempio n. 4
0
def process(request):
    if request.method == 'POST':
        rf = RegisterForm(request.POST)
        if rf.is_valid():
            account = rf.save(commit=False)
            account.password = sha1(rf.cleaned_data['login'].encode('utf-8').lower()+rf.cleaned_data['password'].encode('utf-8')).hexdigest()

            account.id = None
            account.save()
           
            rc = RegisterConfirmation()
            rc.account = account
            rc.key = sha1(str(datetime.now()) + 'ourwearyeyesstillstraytothehorizon').hexdigest()
            while True:     # Make it so key is truly unique
                try:
                    rc.save()
                except IntegrityError:
                    rc.key = sha1(rc.key + 'theteaset' + str(datetime.now())).hexdigest()
                else:
                    break

            resp = render_to_string('register/register/mail.txt', {'key':rc.key,
                                                                   'password':rf.cleaned_data['password'],
                                                                   'login':account.login,
                                                                   'empire':account.empire})
            send(account.email, u'Bellum - aktywacja konta', unicode(resp, 'UTF-8'))

            return render_to_response('register/register/success.html', {})
       
    try:
        rf
    except:
        rf = RegisterForm()
   
    return render_to_response('register/register/register.html', {'form':rf, 'sup':sup})
Esempio n. 5
0
def addposts(request,**args):
    cUser = args['User']
    currentpage = 'posts'
    if request.method == "GET":
        book = request.GET.get("book",0)
        try:
            book = dm.Book.objects.get(id = book)
        except dm.Book.DoesNotExist:
            book = 0
    if request.method == "POST":
        postsdata = {
            "subject" : request.POST["subject"],\
            "content" : request.POST["content"],\
            "book"    : request.POST["book"],\
            "author"  : cUser.id
        }

        if len(postsdata['subject']) == 0:
            subjecterror = u'笔记标题不能为空!'
            return render_to_response('dushu/addposts.html',locals())
        elif len(postsdata['content']) == 0:
            contenterror = u'笔记内容不能为空!'
            return render_to_response('dushu/addposts.html',locals())
        newPosts = dm.Posts.objects.create(**postsdata)
        buildship(int(postsdata['book']),cUser.id)
        return HttpResponseRedirect("/posts/" + str(newPosts.id))
    return render_to_response('dushu/addposts.html',locals())
Esempio n. 6
0
def login(request):
    currentpage = 'user'
    if request.session.get('uid'):
        return HttpResponseRedirect('/')
    ref_page = request.GET.get('ref_page','/')
    if '/reg/' in ref_page:
        ref_page = '/'
    if 'email' in request.POST and 'pwd' in request.POST:
        email = request.POST.get('email')
        pwd   = request.POST.get('pwd')

        if len(email) == 0:
            etips = u'Email地址不能为空!'
        elif len(pwd) == 0:
            ptips = u'密码不能为空!'
        else:
            try:
                user = dm.User.objects.get(email = email)
                right_pwd = user.pwd
            except dm.User.DoesNotExist:
                etips = u'用户不存在!'
            else:
                if right_pwd != md5(pwd).hexdigest():
                    ptips = u'密码错误!'
                else:
                    if user.valid:
                        request.session['uid'] = user.id
                        request.session.set_expiry(0)
                        return HttpResponseRedirect(ref_page)
                    else:
                        return render_to_response('dushu/confirmation.html',locals())
    return render_to_response('dushu/login.html',locals())
Esempio n. 7
0
def edit(request,**args):
    cUser = args['User']
    currentpage = 'posts'
    pid = request.GET.get('pid',0)
    try:
        model = dm.__dict__[args['model'].capitalize()]
    except KeyError:
        raise Http404
    try:
        arc = model.objects.get(id = pid)
        postsid = pid
        try:
            subject = arc.subject
        except AttributeError:
            postsid = arc.posts
            subject = ''
    except model.DoesNotExist:
        error = u"内容不存在"
        return render_to_response("dushu/tips.html",locals())
    if request.method == "POST":
        if args['model'] == 'posts':
            data = {
                'subject':request.POST['subject'],
                'content':request.POST['content']
            }
        elif args['model'] == 'reply':
            data = {'content':request.POST['content']}
        model.objects.filter(id = pid).update(**data)
        return HttpResponseRedirect("/posts/" + str(postsid))
    return render_to_response("dushu/edit.html",locals())
Esempio n. 8
0
def ajax_get_file (request):
	if not valid_session(request):
		return render_to_response('js_play/templates/ajax.html', {'output': 'Error: Invalid session.'})
	file_obj, dir_obj = init_workers(request.session['session_type'])
	if request.method == 'GET':
		file_path = request.GET['file_path']
		current_dir = dir_obj.get_current_dir()
		file_contents = file_obj.get_file_contents(full_file_path = current_dir + file_path, escape_to_html = False)
		return render_to_response('js_play/templates/ajax.html', {'output': file_contents})
	return render_to_response('js_play/templates/ajax.html', {'output': 'Error: Invalid file requested.'})
Esempio n. 9
0
def ajax_save_file (request):
	if not valid_session(request):
		return render_to_response('js_play/templates/ajax.html', {'output': 'Error: Invalid session.'})
	file_obj, dir_obj = init_workers(request.session['session_type'])
	if request.method == 'POST':
		file_contents = request.POST['file_contents']
		file_path = request.POST['file_path']
		current_dir = dir_obj.get_current_dir()
		file_obj.save_file_contents(current_dir + file_path, file_contents)
	return render_to_response('js_play/templates/ajax.html', {'output': ''})
Esempio n. 10
0
def main(request, demo):
    if demo == 'flot':
        return render_to_response('demos/flot.mako', {})
    elif demo == 'rickshaw':
        return render_to_response('demos/rickshaw.mako', {})
    elif demo == 'nvd3':
        return render_to_response('demos/nvd3.mako', {})
    elif demo == 'cubism':
        return render_to_response('demos/cubism.mako', {})
    else:
        return HttpResponse(content="Demo doesn't exist", status=404)
Esempio n. 11
0
def index(request):
    # logged in user
    c = Context()   # duck-typed context object for Mako
    c.ident = request.user
    add_auth_info_to_context(request, c)
    c.silos = list_silos()
   
    if settings.METADATA_EMBARGOED:
        #if not ident:
        #    abort(401, "Not Authorised")
        if request.user.is_authenticated():
            c.silos = authz(ident)
        else:
            return HttpResponseForbidden("Forbidden")

    c.silo_infos = {}
    for silo in c.silos:
        c.silo_infos[silo] = []
        state_info = granary.describe_silo(silo)
        if 'title' in state_info and state_info['title']:
            c.silo_infos[silo].append(state_info['title'])
        else:
            c.silo_infos[silo].append(silo)
        c.silo_infos[silo].append(get_datasets_count(silo))
        c.silo_infos[silo].append(getSiloModifiedDate(silo))
     
    # conneg return
    accept_list = None
    if request.META.has_key('HTTP_ACCEPT'):
        try:
            accept_list = conneg_parse(request.META['HTTP_ACCEPT'])
        except:
            accept_list= [MT("text", "html")]
    if not accept_list:
        accept_list= [MT("text", "html")]
    mimetype = accept_list.pop(0)
    while(mimetype):
        if str(mimetype).lower() in ["text/html", "text/xhtml"]:
            return render_to_response('list_of_silos.html', {'c':c})
        elif str(mimetype).lower() in ["text/plain", "application/json"]:
            response.content_type = 'application/json; charset="UTF-8"'
            response.status_int = 200
            response.status = "200 OK"
            return HttpResponse(json.dumps(c.silos), mimetype='application/json; charset="UTF-8"') 
        try:
            mimetype = accept_list.pop(0)
        except IndexError:
            mimetype = None

    return render_to_response('list_of_silos.html', {'c':c})
Esempio n. 12
0
def addsource(request):
        # A user needs to be authenticated and authorized  to be able to administer the DataFinder                          
        # Test if the user is now a university authenticated user
        if 'DF_USER_SSO_ID' not in request.session:                          
            return redirect("/login?redirectPath=admin")
            # Test if the user is Data Finder authorised user
        if  request.session['DF_USER_ROLE'] != "admin" :
            return redirect("/")
        
        context = {}
        
        if request.GET.has_key('message'):    
            context["message"]=request.GET['message']
        if request.GET.has_key('status'):    
            context["status"]=request.GET['status']    
            
        http_method = request.environ['REQUEST_METHOD'] 
        if http_method == "GET":
            return render_to_response('add_metadata_source.html',context, context_instance=RequestContext(request))
        if http_method == "POST": 
            if request.POST.has_key('source'):
               context["source"] = request.POST["source"]  
               context["title"] = request.POST["title"]  
               context["description"] = request.POST["description"] 
               context["uri"] = request.POST["uri"] 
               context["notes"] = request.POST["notes"] 
               context["activate"] = False
               try:
                    sourceinfo= SourceInfo.objects.get(source=context["source"])                                        
                    context['message']="Sorry, the source " + context["source"] +" already exists." 
                    context['status']="error"
                    return redirect("/admin?message="+context['message']+"&status="+context['status'])              
               except SourceInfo.DoesNotExist,e:
                    sourceinfo = SourceInfo()
                    sourceinfo.source = context["source"]
                    sourceinfo.title = context["title"]
                    sourceinfo.description = context["description"]
                    sourceinfo.uri = context["uri"]                   
                    sourceinfo.notes = context["notes"] 
                    sourceinfo.save()   
                    context['message']="Thanks, "+ request.POST.get("source") +" has been successfully added."
                    context['status']="success"                                    
                    return render_to_response('edit_metadata_source.html',context, context_instance=RequestContext(request))              
               except Exception,e:
                    logger.error("Oops, an error occurred, sorry...")
                    context['message']="Oops, an error occurred, sorry..." 
                    context['status']="error"
                    return redirect("/admin?"+"message="+context['message']+"&status="+context['status'])       
Esempio n. 13
0
def builder(request, template='packager'):
  version = request.GET.get('version', settings.DEFAULT_VERSION)
  dpdr = get_depender(version=version, reset=False)
  packages = {}
  proj = get_version_settings(version)
  #Core, More, etc
  for p in proj['BUILDER_PACKAGES']:
    if not hasattr(packages, p):
      packages[p] = {}
    #Fx, Element, etc
    for name, component in dpdr.packages[p].components.iteritems():
      if not hasattr(packages[p], component.filename):
        packages[p][component.filename] = {
          'provides': [],
          'requires': []
        }
      packages[p][component.filename]['provides'].extend(component.provides)
      packages[p][component.filename]['requires'].extend(component.requires)
  def get_provides(package, filename):
    return [pc[1] for pc in packages[package][filename]['provides']]
  def get_depends(package, filename):
    return [pc[0] + '/' + pc[1] for pc in packages[package][filename]['requires']]
  return render_to_response(template + '.mako',
    {
      'packages': proj['BUILDER_PACKAGES'],
      'package_data': packages,
      'get_provides': get_provides,
      'get_depends': get_depends,
      'dpdr': dpdr,
      'markdown': markdown,
      'version': version
    }
  )
Esempio n. 14
0
def process(request, rankingtype, page):
    if not (rankingtype in ('all', 'mother', 'army', 'allied')):
            return redirect('/')

    rt = {'all':RankingNone, 'army':RankingArmy, 'mother':RankingMother, 'allied':RankingAlliance}

    if page == None:
        # caveats
        pass
    else:
        page = int(page)
        ranking = rt[rankingtype].objects.filter(id__gt=RPP*(page-1)).filter(id__lt=(RPP*page)+1)

    acc = getAccount(request)

    total_objects_count = rt[rankingtype].objects.count()
    pages = int(ceil(total_objects_count / RPP))

    pagination = []

    if (pages < 8):      # special case - static
        pagination = range(1, pages+1)
    elif (page > 3) and (page < pages-2):     # no special cases apply
        pagination = [page-3, page-2, page-1, page, page+1, page+2, page+3]
    elif (page < 4):    # less than 3 entries left
        pagination = range(1, page+1) + [page+1, page+2, page+3]
    elif (page > pages-4):      # less than 3 entries right
        pagination = [page-3, page-2, page-1, page] + range(page+1, pages+1)

    return render_to_response('stats/ranking/'+rankingtype+'.html',{'pgo':PrimaryGUIObject(request),
                                                                    'account':acc,
                                                                    'page':page,
                                                                    'pagecount':pages,
                                                                    'pages':pagination,
                                                                    'ranking':ranking})
Esempio n. 15
0
def mine(request):

    orderitems = OrderItem.objects.select_related('dish__vendor__category').filter(user=request.user.id).order_by('-create_time')
    context = create_context(request,
        orderitems=orderitems,
    )
    return render_to_response('/home/mine.html', context)
Esempio n. 16
0
def show_vendor(request, id):
    try:
        vendor = Vendor.objects.get(id=id)
        context = create_context(request, vendor=vendor)
        return render_to_response('home/show_vendor.html', context)
    except Vendor.DoesNotExist:
        return HttpResponseNotFound('Not Found')
Esempio n. 17
0
def backlogs(request, team_name):
    """
    This view returns the summary of all backlogs under the team umbrella.
    """
    template = 'backlogs.html'
    team = Team.objects.get(name=team_name.lower())
    backlogs = Backlog.objects.filter(team=team.id)
    
    #--------------------------------------------------------------
    items_to_display = team.backlog_items_shown #default # of items to display per backlog
    #--------------------------------------------------------------
    
    mother_backlog_stats = {}
    supplemental_backlog_stats = {}
    
    for backlog in backlogs:
        a = sninjaQuery.sninjaQuery(backlog.backlog)
        project_id = a.getProjectIdFromProjectName()
        if project_id:
            if not backlog.supplemental:
                mother_backlog_stats[backlog.backlog] = {}
                mother_backlog_stats[backlog.backlog]['data'] = a.getTopStories(backlog.supplemental)
                mother_backlog_stats[backlog.backlog]['owner'] = backlog.owner
                mother_backlog_stats[backlog.backlog]['project_id'] = project_id
            if backlog.supplemental:
                supplemental_backlog_stats[backlog.backlog] = {}
                supplemental_backlog_stats[backlog.backlog]['data'] = a.getTopStories(backlog.supplemental)
                supplemental_backlog_stats[backlog.backlog]['owner'] = backlog.owner
                supplemental_backlog_stats[backlog.backlog]['project_id'] = project_id

    # These 3 arrays comprise the three columns that will be created on the html
    # page.  This is a preprocessor for the data.3
    backlog_box1 = {}
    backlog_box2 = {}
    backlog_box3 = {}
    n = 0
    for item in supplemental_backlog_stats.keys():
        print item, n
        if n % 3 == 0:
            backlog_box1[item] = supplemental_backlog_stats[item]
        elif n % 3 == 1:
            backlog_box2[item] = supplemental_backlog_stats[item]
        elif n % 3 == 2:
            backlog_box3[item] = supplemental_backlog_stats[item]
        n += 1
    n = 0
    for item in mother_backlog_stats.keys():
        print item, n
        if n % 3 == 0:
            backlog_box1[item] = mother_backlog_stats[item]
        elif n % 3 == 1:
            backlog_box2[item] = mother_backlog_stats[item]
        elif n % 3 == 2:
            backlog_box3[item] = mother_backlog_stats[item]
        n += 1

    context_data = {'backlog_box1': backlog_box1, 'backlog_box2': backlog_box2, \
                    'backlog_box3': backlog_box3, 'items_to_display': items_to_display, \
                    'media_url':settings.MEDIA_URL}
    return render_to_response(template, context_data)
Esempio n. 18
0
def redirect(request):
    if request.method == 'GET':
        clk_dict = create_clk_dict(request)
        if 'show_type' in clk_dict and clk_dict['show_type'] == 1:
            show_type = 1
        else:
            show_type = 0

        if show_type == 1:
            item = SecKill.get_seckill_link_by_id(clk_dict['link_id'])

        else:
            item = Feeds.get_feed_url_by_linkid(clk_dict['link_id'])
        if item:
            if show_type == 1:
                clk_dict['real_link'] = add_link_id(item['link'])
            else:
                clk_dict['real_link'] = item['link']
            stat_log.info('clk=%s'%json.dumps(dict(clk_dict)))
            response = render_to_response("redirect.html",{'id': clk_dict['feed_id'], 'url': clk_dict['real_link']}, context_instance=RequestContext(request))

            timestamp = str(int(time.time())) + '000'
            message = TAOBAO_APP_SECRET + 'app_key' + TAOBAO_APP_KEY + 'timestamp' + timestamp + TAOBAO_APP_SECRET
            mysign = hmac.new(TAOBAO_APP_SECRET)
            mysign.update(message)
            mysign = mysign.hexdigest().upper()
            set_cookie(response,'timestamp',timestamp)
            set_cookie(response,'sign',mysign)
            
            return response
        else:
            info_log.info('invalid clk url %s'%clk_dict)
            return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/')
Esempio n. 19
0
def home(request):
    (top_feeds,common_feeds) = Feeds.get_all_feeds_ret_2(1,0)
    userinfo = None
    open_id = get_cookie(request,'od')
    if open_id:
        userinfo = UserInfo.get_user_info_by_openid(open_id)
    response = render_to_response("index.html",{'top_feeds': top_feeds, 'common_feeds': common_feeds, 'userinfo': userinfo}, context_instance=RequestContext(request))

    stat_dict={}
    stat_dict['pn'] = 1
    stat_dict['type'] = 0
    if get_cookie(request,'cid'):
        cid = get_cookie(request,'cid')
        info_log.info('cookie %s coming'%cid)
        stat_dict['cid'] = cid
        stat_dict['ua'] = request.META.get('HTTP_USER_AGENT','unknown')
        stat_dict['ip'] = request.META.get('REMOTE_ADDR','unknown')
        stat_log.info('get_home=%s'%json.dumps(dict(stat_dict)))
    else:
        cid = create_cookie_id(request)
        set_cookie(response,'cid',cid)
        info_log.info('create cookie id %s'%cid)
        stat_dict['cid'] = cid
        stat_dict['ua'] = request.META.get('HTTP_USER_AGENT','unknown')
        stat_dict['ip'] = request.META.get('REMOTE_ADDR','unknown')
        stat_log.info('get_home=%s'%json.dumps(dict(stat_dict)))
    return response
Esempio n. 20
0
def home(request):
    args = {
        "user": request.user,
        "login_date": request.session["login_date"],
        "login_method": request.session["login_method"]
    }
    return render_to_response("home.mako", args)
Esempio n. 21
0
def seckill(request):

    if 'req_type' in request.GET and request.GET['req_type'].isdigit():
        req_type = int(request.GET['req_type'])
    else:
        req_type = 3
    order = 1
    page_num = 1
    sec_kills = SecKill.get_return_list(req_type,order,page_num)
    userinfo = None
    open_id = get_cookie(request,'od')
    if open_id:
        userinfo = UserInfo.get_user_info_by_openid(open_id)
    response = render_to_response("seckill.html",{'sec_kills': sec_kills, 'userinfo': userinfo, 'req_type': req_type}, context_instance=RequestContext(request))

    stat_dict={}
    stat_dict['pn'] = 1
    stat_dict['type'] = 0
    if get_cookie(request,'cid'):
        cid = get_cookie(request,'cid')
        info_log.info('cookie %s coming'%cid)
        stat_dict['cid'] = cid
        stat_dict['ua'] = request.META.get('HTTP_USER_AGENT','unknown')
        stat_dict['ip'] = request.META.get('REMOTE_ADDR','unknown')
        stat_log.info('get_seckill_home=%s'%json.dumps(dict(stat_dict)))
    else:
        cid = create_cookie_id(request)
        set_cookie(response,'cid',cid)
        info_log.info('create cookie id %s'%cid)
        stat_dict['cid'] = cid
        stat_dict['ua'] = request.META.get('HTTP_USER_AGENT','unknown')
        stat_dict['ip'] = request.META.get('REMOTE_ADDR','unknown')
        stat_log.info('get_seckill_home=%s'%json.dumps(dict(stat_dict)))
    return response
Esempio n. 22
0
def movie(request, generation, orgname):
    gdir = 'gen-%s' % generation
    gdir = os.path.join(BASEDIR, gdir)
    mpath = get_movie(gdir, orgname)
    url = 'http://www.polymerase.org/~ghall/coindrop/movies/%s.flv' % orgname
    macros = {'movie_url': url}
    return render_to_response('movie.tmpl', macros)
Esempio n. 23
0
def login(request):
    '''login view'''
    if request.session.get("uid"):
        return HttpResponseRedirect("/")

    ref_page = request.GET.get('ref_page','/')

    if "usm" in request.POST and "pwd" in request.POST:
        usm = request.POST["usm"]
        pwd = request.POST["pwd"]
        if len(usm) == 0:
            utips = u'用户名不能为空!'
        elif len(pwd) == 0:
            ptips = u'密码不能为空!'
        else:
            try:
                user = sm.User.objects.get(usm = usm)
                right_pwd = user.pwd
            except sm.User.DoesNotExist:
                utips = u'用户不存在!'
            else:
                #if right_pwd != md5(pwd).hexdigest():
                if right_pwd != pwd:
                    ptips = u'密码错误!'
                else:
                    request.session['uid'] = user.id
                    request.session.set_expiry(0)
                    return HttpResponseRedirect(ref_page)
    return render_to_response("system/login.html",locals())
Esempio n. 24
0
def process(request):
    if request.method == 'POST':
        rf = RemindForm(request.POST)
        if rf.is_valid():
            acc = Account.objects.get(email=rf.cleaned_data['email'])
            if acc.passwordremindtoken_set.count() > 0:
                acc.passwordremindtoken_set.all().delete()
                didRemovePrevious = True
            else:
                didRemovePrevious = False
            prt = PasswordRemindToken(account=acc)

            prt.key = sha1(str(datetime.now()) + 'thelightwasbrighter').hexdigest()
            while True:     # Make it so key is truly unique
                try:
                    prt.save()      # chance is 1:2^160 that key repeats, but the chance is
                except IntegrityError:
                    prt.key = sha1(prt.key + 'hellocharlie' + str(datetime.now())).hexdigest()
                else:
                    break
            try:
                resp = render_to_string('register/passremind/mail.txt', {'key':prt.key,
                                                                         'login':acc.login,
                                                                         'accname':acc.empire,
                                                                         'newpass':prt.newpassword})
                send(acc.email, u'Bellum - przypomnienie hasła', unicode(resp, 'UTF-8'))
            except Exception, e:
                # something has FEHLED
                prt.delete()
                raise e
            return render_to_response('register/passremind/success.html', {'key':prt.key,
                                                            'newpassword':prt.newpassword,
                                                            'didRemovePrevious':didRemovePrevious})
Esempio n. 25
0
def home(request):
  args = {
    "user": request.user,
    "login_date": request.session["login_date"],
    "login_method": request.session["login_method"]
  }
  return render_to_response("home.mako", args)
Esempio n. 26
0
def sensors_list(request):
    sensors = Sensor.objects.filter(
        Device=request.session['Device.id']).order_by('sorting')
    return render_to_response('device/setup.sensors_list.html', {
        'request': request,
        'sensors': sensors
    })
Esempio n. 27
0
def index(request):
    logger.error(_('error log test'))
    logger.info(_('info log test'))
    logger.debug(_('debug log test'))
    context = {}
    context.update(csrf(request))
    return render_to_response('index.html', context)
Esempio n. 28
0
def toc(request, path):
  toc = get_toc(_read_md(path)[0])
  basepath = request.REQUEST.get('basepath')
  return render_to_response('toc.mako',{
    'basepath': basepath,
    'toc': toc
  })
Esempio n. 29
0
def process(request):
    mum = getCurrentMother(request)
    tech = getTechnology(request)

    try:
        mro, = MotherRelocationOrder.objects.filter(mother=mum)
    except:
        relocating = False
        mro = None
    else:
        relocating = True
    constructions = mum.getConstructions()
    researches = mum.getResearches()

    return render_to_response('mother/overview/overview.html', {'mother':mum,
                                                                'constructions':constructions,
                                                                'c_requirements':mother_construction.getRequirementsArray(mum, getRace(request)),
                                                                'c_costs':mother_construction.getCostsArray(mum, getRace(request)),
                                                                'technology':tech,
                                                                'researches':researches,
                                                                't_costs':technology.getCostsArray(tech, getRace(request)),
                                                                't_requirements':technology.getRequirementsArray(tech, getRace(request)),
                                                                'pgo':PrimaryGUIObject(request),
                                                                'relocating':relocating,
                                                                'mro':mro,
                                                                'race':getRace(request),
                                                                })
Esempio n. 30
0
def process(request):
    struct = get_struct(request).exports
    if request.method == 'POST':
        rf = DatepickForm(request.POST)
        rf.fields['method'].choices = struct.EXPORTS(DATEPICK_PRESENTATION)
        if rf.is_valid():
            s = int(rf.cleaned_data['method'])
            if s == 0:
                from p24ip.arch.sopmods import excel
                return excel.process(request, rf.cleaned_data['dfrom'],
                                     rf.cleaned_data['dto'])
            if s == 1:
                from p24ip.arch.sopmods import extrema
                return extrema.process(request, rf.cleaned_data['dfrom'],
                                       rf.cleaned_data['dto'])
            else:
                return struct.__dict__['export' + str(s)](
                    request, rf.cleaned_data['dfrom'], rf.cleaned_data['dto'])

    else:
        rf = DatepickForm()
        rf.fields['method'].choices = struct.EXPORTS(DATEPICK_PRESENTATION)
    return render_to_response('arch/export_datepick.html', {
        'request': request,
        'form': rf
    })
Esempio n. 31
0
def vote_view(request, type, entry_id):
    entry = get_object_or_404(Entry, id=entry_id)
    if type == "goodnews":
        entry.good += 1
    elif type == "badnews":
        entry.bad += 1
    entry.save()
    return render_to_response( get_template_name('blank.html'),{})
Esempio n. 32
0
def ideamaker(request):
    template = 'ideas.html'
    
    idea_form = IdeaForm()
    all_ideas = Idea.objects.all().order_by('-id')[:25]

    context_data = {'idea_form':idea_form,'ideas':all_ideas,'configs':configs}
    return render_to_response(template, context_data)
Esempio n. 33
0
def rights_flags(request,rights_number):
    template = 'rights.html'

    releasesObject = new_releases_tool.NewReleasesTool()
    rights_data = releasesObject.returnRightsFlags(rights_number)

    context_data = {'rights':rights_data, 'configs':configs}
    return render_to_response(template, context_data)
Esempio n. 34
0
def batchmaker(request):
    template = 'batchmaker.html'
    
    batch_form = BatchForm()
    all_batches = Batch.objects.all().order_by('-id')[:25]

    context_data = {'batch_form':batch_form,'batches':all_batches,'configs':configs}
    return render_to_response(template, context_data)
Esempio n. 35
0
def contacto(request):
    arrayFotos = []

    if 'q' in request.GET and request.GET['q']:
        get = request.GET['q']
        print(get)

    if request.method == 'POST':

        formulario = fotosPedido(request.POST)
        formulario2 = ContactForm(request.POST)
        galletas = ""

        if (get == "1"):

            if formulario.is_valid():

                galletas = request.POST['hidden_field0']
                galletas = galletas.split('|')

                #Imprime url
                #print(galletas)
                global tipoGalleta
                tipoGalleta = galletas[-1]
                galletas.pop()

                tipoGalleta = tipoGalleta[-5]

                descargaAndPaste(galletas, "archivoSal.jpg")

        elif (get == "2"):

            print("Enviar mensaje")
            titulo = 'Mensaje de contacto desde \"Social Cookies\"'
            contenido = request.POST['mensaje'] + "\n"
            contenido += 'Comunicarse a : ' + request.POST['correo'] + "\n"
            contenido += 'A escogido el tipo de galleta: ' "<" + str(
                tipoGalleta) + ">"

            mandaCorreo(titulo, contenido)

            return HttpResponseRedirect('/socialcookies')

    else:
        formulario = ContactForm()
        formulario2 = fotosPedido()

    return render_to_response(
        'index.html', {
            'path': '/static/',
            'seccion': 'contacto',
            'formulario': formulario,
            'formulario2': formulario2,
            "csrftoken": csrf(request)["csrf_token"],
            'fich': ficheros
        })
Esempio n. 36
0
def api_view(request, api_name):
    # logged in user
    c = create_context(request.user)
    c.ident = request.user
    add_auth_info_to_context(request, c)
    if api_name not in ['silos', 'datasets', 'states', 'items']:
        # redirect(url(controller="api", action="apiview", api_name="silos"))
        return redirect("/api/silos")
    c.api_file = "%s_api.html" % api_name
    return render_to_response('/api.html', {'c': c})
Esempio n. 37
0
def index(request):
    fotosE = os.listdir('./socialcookies/static/img/authors')
    fotosE.sort()

    return render_to_response('index.html', {
        'path': '/static/',
        'seccion': 'index',
        'fich': ficheros,
        'fotos': fotosE
    })
Esempio n. 38
0
def red(request):

    d = Device(request.session['Device.dev_number'])
    a = d.alerts
    d.registry['alert'] = '0'
    return render_to_response('device/alertlog.html', {
        'request': request,
        'alerts': a,
        'severity': 1
    })
Esempio n. 39
0
def display(request):
    if request.session['AccountDevice.privileges'] == 0:
        sensors = Sensor.objects.filter(
            Device=request.session['Device.id']).filter(
                canUserRead=True).order_by('sorting')
    else:
        sensors = Sensor.objects.filter(
            Device=request.session['Device.id']).order_by('sorting')
    return render_to_response('device/control.html', {
        'request': request,
        'sensors': sensors
    })
Esempio n. 40
0
def process(request):
    dev = Device.objects.get(id=request.session['Device.id'])
    xd = p24.Device(dev.dev_number)
    struct = get_struct(request)
    af = AFDevice(dev.dev_number)
    return render_to_response(
        'device/overview.html', {
            'dev': dev,
            'request': request,
            'vendor': xd.vendor,
            'struct': struct,
            'af': af
        })
Esempio n. 41
0
def control(request):
    from patelnia.p24 import PerDeviceRegistry
    r = PerDeviceRegistry(request.session['Device.dev_number'])
    if request.session['AccountDevice.privileges'] == 0:
        sensors = Sensor.objects.filter(
            Device=request.session['Device.id']).filter(canUserRead=True)
    else:
        sensors = Sensor.objects.filter(Device=request.session['Device.id'])
    return render_to_response('structures/rx910smartu1/control.html', {
        'request': request,
        'registry': r,
        'sensors': sensors
    })
Esempio n. 42
0
def sensor_new(request):
    af = SensorForm()
    if request.method == "POST":
        af = SensorForm(request.POST)
        af.instance.Device = Device.objects.get(
            id=request.session['Device.id'])
        if af.is_valid():
            af.save()
            return render_to_response('device/setup.sensor_new.html', {
                'request': request,
                'form': af,
                'saved': True
            })
    try:
        af
    except:
        af = SensorForm()

    return render_to_response('device/setup.sensor_new.html', {
        'request': request,
        'form': af,
        'saved': False
    })
Esempio n. 43
0
def render_html_or_json(request, c, template_name, json_obj):
    # conneg return
    accept_list = None
    if request.META.has_key('HTTP_ACCEPT'):
        try:
            accept_list = parse(request.META['HTTP_ACCEPT'])
        except:
            accept_list = [MimeType("text", "html")]
    if not accept_list:
        accept_list = [MimeType("text", "html")]
    mimetype = accept_list.pop(0)
    while (mimetype):
        if str(mimetype).lower() in ["text/html", "text/xhtml"]:
            return render_to_response(template_name, {'c': c})
        elif str(mimetype).lower() in ["text/plain", "application/json"]:
            return HttpResponse(json.dumps(json_obj),
                                mimetype='application/json; charset="UTF-8"')
        try:
            mimetype = accept_list.pop(0)
        except IndexError:
            mimetype = None

    return render_to_response(template_name, {'c': c})
Esempio n. 44
0
def sensor_edit(request, sensor_id):
    app = Sensor.objects.get(id=sensor_id)
    if app.Device.id != request.session['Device.id']:
        return redirect('/manage/pick/')
    af = SensorForm(instance=app)
    if request.method == "POST":
        af = SensorForm(request.POST, instance=app)
        if af.is_valid():
            af.save()
            return render_to_response('device/setup.sensor_edit.html', {
                'request': request,
                'form': af,
                'saved': True
            })
    try:
        af
    except:
        af = SensorForm()

    return render_to_response('device/setup.sensor_edit.html', {
        'request': request,
        'form': af,
        'saved': False
    })
Esempio n. 45
0
def save(request):
    from afruntime import DEVDB_ROOT
    from patelnia.p24 import Device
    sensors = Sensor.objects.filter(Device=request.session['Device.id'])
    xie = open(
        DEVDB_ROOT + str(request.session['Device.dev_number']) + '/CONFIG',
        'w')
    for sensor in sensors:
        xie.write(str(sensor.modbus_devid) + " ")
        xie.write(str(sensor.regtype) + " ")
        xie.write(str(sensor.register) + " ")
        xie.write(str(sensor.interval_0) + " ")
        xie.write(str(sensor.interval_1) + "\n")
    del xie
    Device(request.session['Device.dev_number']).reread_sensorics()
    return render_to_response('device/setup.save.html', {'request': request})
Esempio n. 46
0
def network_info(request):
    import subprocess
    commands = [
        "route -n",
        "getent ahosts",
        "ip addr",
        "cat /etc/resolv.conf",
        "cat /etc/hosts",
        "ps aux | grep java",
        "netstat -lnp",
    ]

    netinfo = dict(
        (cmd, subprocess.check_output(cmd, shell=True)) for cmd in commands)

    return render_to_response("netinfo.html", {'info': netinfo})
Esempio n. 47
0
def process(request):
    if request.method == 'POST':
        lf = LoginForm(request.POST)
        if lf.is_valid():
            acc = Account.objects.get(login=lf.cleaned_data['login'])
            request.session['logged'] = True
            request.session['Account.id'] = acc.id
            request.session['Account.privileges'] = acc.privileges
            request.session['device_picked'] = False
            return redirect('/manage/pick/')
    try:
        lf
    except:
        lf = LoginForm()

    return render_to_response('login/login.html', {
        'form': lf,
        'request': request
    })
Esempio n. 48
0
def tutorials(request):
    location = settings.CONTENT_FRAME_URL() % request.get_host().split(':')[0]
    step_location = "/lesson/"
    if request.user.is_authenticated() \
        and request.user.username != "AnonymousUser":
        try:
            ustep = UserLocation.objects.get(user=request.user)
            hue_location = ustep.hue_location
            step_location = ustep.step_location
            if step_location == None:
                step_location = "/lesson/"
            if urlparse(hue_location).netloc == urlparse(location).netloc:
                location = hue_location
        except UserLocation.DoesNotExist:
            pass

    return render_to_response("sandbox-tutorials/frames.html", {
        'content': location,
        'step_location': step_location
    })
Esempio n. 49
0
def process(request, dfrom, dto):
    # Prepare reads

    archsensors = ArchSensor.objects.filter(
        Sensor__Device__id=request.session['Device.id'])

    sheets = {}

    for archsensor in archsensors:

        minimo = archsensor.read_set.filter(readed_on__lte=dto).filter(
            readed_on__gte=dfrom).exclude(data=None).order_by('data')[0]
        maximo = archsensor.read_set.filter(readed_on__lte=dto).filter(
            readed_on__gte=dfrom).exclude(data=None).order_by('-data')[0]

        sheets[archsensor.Sensor.name] = (minimo, maximo)

    return render_to_response('arch/sopmods/extrema.html', {
        'request': request,
        'reads': sheets
    })
Esempio n. 50
0
def login_handler(request):
    c = Context()  # duck-typed context object for Mako
    c.came_from = request.GET.get('came_from', "/")

    if request.method == "POST":
        if request.POST.has_key('login') and request.POST.has_key('password'):
            username = request.POST['login']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    # Redirect to a success page.
                    return redirect('/welcome')
                else:
                    # Return a 'disabled account' error message
                    request.session[
                        'login_flash'] = """Your account is currently disabled. Please contact the administrator."""
            else:
                # Return an 'invalid login' error message.
                request.session[
                    'login_flash'] = """Wrong credentials. Have you been registered?"""

    return render_to_response("login.html", {'c': c, 'request': request})
Esempio n. 51
0
def about(request):
    return render_to_response('publica/about.html', {})
Esempio n. 52
0
def index(request):
    return render_to_response('publica/index.html', {})
Esempio n. 53
0
def process(request):
    return render_to_response('manage/registry.html', {
        'request': request,
        'registry': GlobalRegistry()
    })
Esempio n. 54
0
def render_to_response(template_name, context):
    context['static'] = settings.STATIC_URL
    return shortcuts.render_to_response(template_name, context)
Esempio n. 55
0
 def testhello(self):
     print render_to_response('hello.html', {'name': 'sand'})
Esempio n. 56
0
def dataset_view(request, siloname, id):
    if not granary.issilo(siloname):
        raise Http404

    rdfsilo = granary.get_rdf_silo(siloname)
    if not rdfsilo.exists(id):
        raise Http404

    c = Context()
    silo = siloname
    #tmpl_context variables needed: c.silo_name, c.zipfiles, c.ident, c.id, c.path
    c.silo_name = siloname
    c.id = id
    ident = request.user
    c.ident = ident.username
    dataset = rdfsilo.get_item(id)

    creator = None
    if dataset.manifest and dataset.manifest.state and 'metadata' in dataset.manifest.state and dataset.manifest.state['metadata'] and \
                                   'createdby' in dataset.manifest.state['metadata'] and dataset.manifest.state['metadata']['createdby']:
        creator = dataset.manifest.state['metadata']['createdby']

    http_method = request.method

    if http_method == "GET":
        c.editor = False
        if settings.METADATA_EMBARGOED:
            if not ident:
                return HttpResponse("Not Authorised", status=401)
            silos = authz(ident)
            if silo not in silos:
                return HttpResponseForbidden("Forbidden")
            silos_admin = authz(ident, permission='administrator')
            silos_manager = authz(ident, permission='manager')
            if c.ident == creator or silo in silos_admin or silo in silos_manager:
                c.editor = True
        elif ident:
            silos = authz(ident)
            if silo in silos:
                silos_admin = authz(ident, permission='administrator')
                silos_manager = authz(ident, permission='manager')
                if ident[
                        'repoze.who.userid'] == creator or silo in silos_admin or silo in silos_manager:
                    c.editor = True
    else:
        #identity management of item
        if not ident:
            return HttpResponse("Not Authorised", status=401)
        silos = authz(ident)
        if silo not in silos:
            return HttpResponseForbidden("Forbidden")
        silos_admin = authz(ident, permission='administrator')
        silos_manager = authz(ident, permission='manager')
        if not (c.ident == creator or silo in silos_admin
                or silo in silos_manager):
            return HttpResponseForbidden("Forbidden")

    if http_method == "GET":
        c.zipfiles = get_zipfiles_in_dataset(dataset)
        # conneg return
        accept_list = None
        if 'HTTP_ACCEPT' in request.META:
            try:
                accept_list = conneg_parse(request.META['HTTP_ACCEPT'])
            except:
                accept_list = [MT("text", "html")]
        if not accept_list:
            accept_list = [MT("text", "html")]
        mimetype = accept_list.pop(0)
        while (mimetype):
            if str(mimetype).lower() in ["text/html", "text/xhtml"]:
                return render_to_response("/list_of_zipfiles.html", {
                    'c': c,
                })
            elif str(mimetype).lower() in ["text/plain", "application/json"]:
                return HttpResponse(
                    json.dumps(list(c.zipfiles.keys())),
                    mimetype='application/json; charset="UTF-8"')
            try:
                mimetype = accept_list.pop(0)
            except IndexError:
                mimetype = None
        #Whoops nothing satisfies - return text/html
        return render_to_response("/list_of_zipfiles.html", {
            'c': c,
        })
    elif http_method == "POST":
        params = request.POST
        if not (params.has_key("filename") and params['filename']):
            return HttpResponse("You must supply a filename to unpack",
                                status=400)

        item_real_filepath = dataset.to_dirpath()
        target_filepath = "%s/%s" % (item_real_filepath, params['filename'])
        if not os.path.isfile(target_filepath):
            return HttpResponse("File to unpack not found", status=404)
        if not check_file_mimetype(target_filepath, 'application/zip'):
            return HttpResponse("File is not of type application/zip",
                                status=415)

        if params.has_key("id") and params['id']:
            target_dataset_name = params['id']
        else:
            target_dataset_name = id

        #step 1: Create / initialize target dataset
        if not rdfsilo.exists(target_dataset_name):
            if not allowable_id2(target_dataset_name):
                return HttpResponse(
                    "Data package name can contain only the following characters - %s and has to be more than 1 character"
                    % ag.naming_rule_humanized,
                    status=400,
                    mimetype="text/plain")
            target_dataset = create_new(rdfsilo, target_dataset_name, c.ident)
            hr = HttpResponse("Created", status=201, mimetype="text/plain")
            hr["Content-Location"] = reverse("dataset_view",
                                             kwargs={
                                                 'siloname': siloname,
                                                 'id': target_dataset_name
                                             })
        else:
            hr = HttpResponse("204 Updated", status=204, mimetype="text/plain")
            target_dataset = rdfsilo.get_item(target_dataset_name)

        #step 2: Unpack zip item

        try:
            unpack_zip_item(target_dataset, dataset, params['filename'],
                            rdfsilo, c.ident)
        except BadZipfile:
            return HttpResponse("BadZipfile: Couldn't unpack zipfile",
                                status=400,
                                mimetype="text/plain")

        # FIXME: err.. wat is this?!
        target_dataset.sync()
        target_dataset.sync()
        target_dataset.sync()

        if hr.status == 201:
            try:
                b.creation(silo, id, ident=c.ident)
            except:
                pass
        else:
            try:
                b.change(silo, id, ident=c.ident)
            except:
                pass

        # conneg return
        accept_list = None
        if 'HTTP_ACCEPT' in request.META:
            try:
                accept_list = conneg_parse(request.META['HTTP_ACCEPT'])
            except:
                accept_list = [MT("text", "html")]
        if not accept_list:
            accept_list = [MT("text", "html")]
        mimetype = accept_list.pop(0)
        while (mimetype):
            if str(mimetype).lower() in ["text/html", "text/xhtml"]:
                return redirect(
                    reverse("dataset_view", kwargs={
                        'silo': silo,
                        'id': id
                    }))
            elif str(mimetype).lower() in ["text/plain", "application/json"]:
                hr.mimetype = "text/plain"
                return hr
            try:
                mimetype = accept_list.pop(0)
            except IndexError:
                mimetype = None
        # Whoops - nothing satisfies - return text/plain
        hr.mimetype = "text/plain"
        return hr
Esempio n. 57
0
def sitemap(request):
    return render_to_response('sitemap.xml', {})
Esempio n. 58
0
def process_list(request):
    ads = AccountDevice.objects.filter(Account=request.session['Account.id'])
    return render_to_response('manage/pick.list.html', {
        'ads': ads,
        'request': request
    })
Esempio n. 59
0
def mako_html(request):
    context = {
        't': 'for test',
    }
    return render_to_response('misc/mako_html.html', context)
Esempio n. 60
0
def process(request):
    return render_to_response(
        'device/registry.html', {
            'request': request,
            'registry': Device(request.session['Device.dev_number']).registry
        })