示例#1
0
def admin_delete_user(request, environment, session, username):
    """
    deletes <username>'s user object from the database

    Possible errortypes are:
     *
    1May raise the following Exceptions:
     *
    """
    # don't delete admin user
    if username == 'admin':
        return render_template("admin_delete_user.htmljinja", environment,
                               success=False)

    try:
        user = get_user_obj(username, session)
    except NoResultFound:
        return render_template("admin_delete_user.htmljinja", environment,
                               success=False)  # delete all posts by user
    posts = session.query(model.post).filter(model.post.owner == user).all()
    for post in posts:
        session.delete(post)
    # delete friends
    #for friend in user.friends:
        #session.delete(friend)
    session.delete(user)
    session.commit()

    return redirect('/admin/users/view')
示例#2
0
def admin_create_user(request, environment, session):
    """
    creates a new user and adds it to the database.

    Possible errortypes are:
     *
    May raise the following Exceptions:
     *
    """
    class CreateUserForm(Form):
        username = TextField('Username', [validators.Required()])
        password = TextField('Password', [validators.Required()])

    if request.method == 'POST':
        form = CreateUserForm(request.form)
        if form.validate():
            username = form.username.data.strip()
            password = form.password.data
            #TODO: hash password
            u = model.user(username, password)
            session.add(u)
            try:
                session.commit()
            except IntegrityError:
                return render_template("admin_create_user.htmljinja",
                                       environment, success=False, form=form)

            return redirect('/admin/users/view')
        else:
            return render_template("admin_create_user.htmljinja", environment,
                                   success=False, form=form)
    else:
        form = CreateUserForm()
        return render_template("admin_create_user.htmljinja", environment,
                               form=form)
示例#3
0
def generate_type_maps(install_dir):
    # Collect legacy code
    tmp = StringIO()
    c_type_maps.gen_length_array(tmp)

    with template_utils.open_output(install_dir, "loci/src/of_type_maps.c") as out:
        util.render_template(out, "of_type_maps.c", legacy_code=tmp.getvalue())
示例#4
0
    def get(self, hash, extension=None):
        q = Album.all().filter('hash =', hash)
        album = q.get()
        if album:
            if extension:
                return self.error(404)
            
            q = Image.all().filter('album =', album)
            return self.response.out.write(render_template('album.html', {
                'name': album.name,
                'images': q,
            }))

        q = Image.all().filter('hash =', hash)
        image = q.get()
        if image:
            if not extension:
                return self.response.out.write(render_template('image.html',
                    { 'image': image }))
            elif image.extension == extension:
                return write_image(self, image.image_data, extension)
            else:
                return self.error(404)
        
        return self.error(404)
示例#5
0
def generate_lists(install_dir):
    # Collect all the lists in use
    list_oftypes = set()
    for uclass in loxi_globals.unified.classes:
        for ofclass in uclass.version_classes.values():
            for m in ofclass.members:
                if isinstance(m, ir.OFDataMember) and \
                        loxi_utils.oftype_is_list(m.oftype):
                    list_oftypes.add(m.oftype)

    for oftype in sorted(list(list_oftypes)):
        cls, e_cls = loxi_utils_legacy.list_name_extract(oftype)
        e_cls = e_cls[:-2]
        e_uclass = loxi_globals.unified.class_by_name(e_cls)
        with template_utils.open_output(install_dir,
                                        "loci/src/%s.c" % cls) as out:
            util.render_template(
                out,
                "list.c",
                cls=cls,
                e_cls=e_cls,
                e_uclass=e_uclass,
                wire_length_get=class_metadata_dict[e_cls].wire_length_get)
            # Append legacy generated code
            c_code_gen.gen_new_function_definitions(out, cls)
示例#6
0
文件: codegen.py 项目: ederlf/loxigen
def generate_common(out, name, version):
    ofclasses = [x for x in build_ofclasses(version)
                 if not utils.class_is_message(x.name)
                    and not utils.class_is_action(x.name)
                    and not utils.class_is_oxm(x.name)
                    and not utils.class_is_list(x.name)]
    util.render_template(out, 'common.py', ofclasses=ofclasses, version=version)
示例#7
0
def generate_message(out, name, version):
    ofclasses = [
        x for x in build_ofclasses(version) if utils.class_is_message(x.name)
    ]
    util.render_template(out,
                         'message.py',
                         ofclasses=ofclasses,
                         version=version)
示例#8
0
def generate_type_maps(install_dir):
    # Collect legacy code
    tmp = StringIO()
    c_type_maps.gen_length_array(tmp)

    with template_utils.open_output(install_dir,
                                    "loci/src/of_type_maps.c") as out:
        util.render_template(out, "of_type_maps.c", legacy_code=tmp.getvalue())
示例#9
0
文件: codegen.py 项目: Taejun/loxigen
def generate_lists(install_dir):
    for cls in of_g.ordered_list_objects:
        with template_utils.open_output(install_dir, "loci/src/%s.c" % cls) as out:
            util.render_template(out, "class.c",
                push_wire_types_data=None)
            # Append legacy generated code
            c_code_gen.gen_new_function_definitions(out, cls)
            c_code_gen.gen_list_accessors(out, cls)
示例#10
0
文件: codegen.py 项目: Taejun/loxigen
def generate_classes(install_dir):
    for uclass in loxi_globals.unified.classes:
        with template_utils.open_output(install_dir, "loci/src/%s.c" % uclass.name) as out:
            util.render_template(out, "class.c",
                push_wire_types_data=push_wire_types_data(uclass))
            # Append legacy generated code
            c_code_gen.gen_new_function_definitions(out, uclass.name)
            c_code_gen.gen_accessor_definitions(out, uclass.name)
示例#11
0
def generate_action(out, name, version):
    ofclasses = [
        x for x in build_ofclasses(version) if utils.class_is_action(x.name)
    ]
    util.render_template(out,
                         'action.py',
                         ofclasses=ofclasses,
                         version=version)
示例#12
0
def generate_lists(install_dir):
    for cls in of_g.ordered_list_objects:
        with template_utils.open_output(install_dir, "loci/src/%s.c" % cls) as out:
            util.render_template(out, "class.c",
                push_wire_types_data=None,
                parse_wire_types_data=None)
            # Append legacy generated code
            c_code_gen.gen_new_function_definitions(out, cls)
            c_code_gen.gen_list_accessors(out, cls)
示例#13
0
def generate_classes(install_dir):
    for i, chunk in enumerate(chunks(loxi_globals.unified.classes, CLASS_CHUNK_SIZE)):
        with template_utils.open_output(install_dir, "loci/src/class%02d.c" % i) as out:
            for uclass in chunk:
                util.render_template(out, "class.c",
                    push_wire_types_data=push_wire_types_data(uclass))
                # Append legacy generated code
                c_code_gen.gen_new_function_definitions(out, uclass.name)
                c_code_gen.gen_accessor_definitions(out, uclass.name)
示例#14
0
文件: codegen.py 项目: Taejun/loxigen
def generate_header_classes(install_dir):
    for cls in of_g.standard_class_order:
        if cls.find("_header") < 0:
            continue
        with template_utils.open_output(install_dir, "loci/src/%s.c" % cls) as out:
            util.render_template(out, "class.c",
                push_wire_types_data=None)
            # Append legacy generated code
            c_code_gen.gen_new_function_definitions(out, cls)
            c_code_gen.gen_accessor_definitions(out, cls)
示例#15
0
def generate_classes(install_dir):
    for i, chunk in enumerate(chunks(loxi_globals.unified.classes, CLASS_CHUNK_SIZE)):
        with template_utils.open_output(install_dir, "loci/src/class%02d.c" % i) as out:
            for uclass in chunk:
                util.render_template(out, "class.c",
                    push_wire_types_data=push_wire_types_data(uclass),
                    parse_wire_types_data=parse_wire_types_data(uclass))
                # Append legacy generated code
                c_code_gen.gen_new_function_definitions(out, uclass.name)
                c_code_gen.gen_accessor_definitions(out, uclass.name)
示例#16
0
def generate_class_metadata(install_dir):
    with template_utils.open_output(
            install_dir, "loci/inc/loci/loci_class_metadata.h") as out:
        util.render_template(out, "loci_class_metadata.h")

    with template_utils.open_output(install_dir,
                                    "loci/src/loci_class_metadata.c") as out:
        util.render_template(out,
                             "loci_class_metadata.c",
                             class_metadata=class_metadata)
示例#17
0
def generate_classes_header(install_dir):
    # Collect legacy code
    tmp = StringIO()
    c_code_gen.gen_struct_typedefs(tmp)
    c_code_gen.gen_new_function_declarations(tmp)
    c_code_gen.gen_accessor_declarations(tmp)

    with template_utils.open_output(install_dir, "loci/inc/loci/loci_classes.h") as out:
        util.render_template(out, "loci_classes.h",
            legacy_code=tmp.getvalue())
示例#18
0
def generate_classes_header(install_dir):
    # Collect legacy code
    tmp = StringIO()
    c_code_gen.gen_struct_typedefs(tmp)
    c_code_gen.gen_new_function_declarations(tmp)
    c_code_gen.gen_accessor_declarations(tmp)

    with template_utils.open_output(install_dir,
                                    "loci/inc/loci/loci_classes.h") as out:
        util.render_template(out, "loci_classes.h", legacy_code=tmp.getvalue())
示例#19
0
def generate_const(out, name, version):
    groups = {}
    for (group, idents) in of_g.identifiers_by_group.items():
        items = []
        for ident in idents:
            info = of_g.identifiers[ident]
            if version in info["values_by_version"]:
                items.append((info["ofp_name"], info["values_by_version"][version]))
        if items:
            groups[group] = items
    util.render_template(out, 'const.py', version=version, groups=groups)
示例#20
0
def generate_strings(install_dir):
    object_id_strs = []
    object_id_strs.append("of_object")
    object_id_strs.extend(of_g.ordered_messages)
    object_id_strs.extend(of_g.ordered_non_messages)
    object_id_strs.extend(of_g.ordered_list_objects)
    object_id_strs.extend(of_g.ordered_pseudo_objects)
    object_id_strs.append("of_unknown_object")

    with template_utils.open_output(install_dir, "loci/src/loci_strings.c") as out:
        util.render_template(out, "loci_strings.c", object_id_strs=object_id_strs)
示例#21
0
def generate_header_classes(install_dir):
    for cls in of_g.standard_class_order:
        if cls.find("_header") < 0 or cls in ["of_header", "of_bsn_header", "of_nicira_header"]:
            continue
        with template_utils.open_output(install_dir, "loci/src/%s.c" % cls) as out:
            util.render_template(out, "class.c",
                push_wire_types_data=None,
                parse_wire_types_data=None)
            # Append legacy generated code
            c_code_gen.gen_new_function_definitions(out, cls)
            c_code_gen.gen_accessor_definitions(out, cls)
示例#22
0
def generate_strings(install_dir):
    object_id_strs = []
    object_id_strs.append("of_object")
    object_id_strs.extend(of_g.ordered_messages)
    object_id_strs.extend(of_g.ordered_non_messages)
    object_id_strs.extend(of_g.ordered_list_objects)
    object_id_strs.extend(of_g.ordered_pseudo_objects)
    object_id_strs.append("of_unknown_object")

    with template_utils.open_output(install_dir, "loci/src/loci_strings.c") as out:
        util.render_template(out, "loci_strings.c", object_id_strs=object_id_strs)
示例#23
0
 def get(self):
     util.save_url(self.request, self.response)
     util.fill_app_attrs(self.app, self.request.uri)
     label = self.request.get("label", default_value=None)
     page = int(self.request.get("page", default_value="1"))
     if page > 0:
         self.fill_view_attrs(label, page)
         self.response.out.write(util.render_template(self.app, self.view))
     else:
         self.view = info.MetaInfoView()
         self.fill_metainfo(label)
         self.response.out.write(util.render_template(self.app, self.view))
示例#24
0
def generate_common(out, name, version):
    ofclasses = [
        x for x in build_ofclasses(version)
        if not utils.class_is_message(x.name) and not utils.class_is_action(
            x.name) and not utils.class_is_instruction(x.name)
        and not utils.class_is_meter_band(x.name)
        and not utils.class_is_oxm(x.name) and not utils.class_is_list(x.name)
    ]
    util.render_template(out,
                         'common.py',
                         ofclasses=ofclasses,
                         version=version)
示例#25
0
def web_view_user_posts(request, environment, session, username, page=1,
                        posts_per_page=15):
    """
    returns the <page> <posts_per_page> posts created by <username> as 'posts',
    <username>'s user object as 'user', an empty array if there aren't any.

    Possible errortype values are:
    * 'NoSuchUser' if <username> is unknown to the system.

    May raise the following Exceptions:
    * Exception('NoSuchUser')
    """

    u = get_user_obj(username, session)

    own = session.query(post.id).filter(post.owner == u.identity).subquery()
    reposts = session.query(post.id).filter(
        post.reposters.contains(u.identity)).subquery()
    total_num = session.query(model.post).filter(or_(post.id.in_(reposts), post.id.in_(own))).count()
    allposts = session.query(model.post).filter(
        or_(post.id.in_(reposts), post.id.in_(own))).order_by(desc(post.timestamp)).offset((page-1)*posts_per_page).limit(posts_per_page).all()

    posts = [p.downcast() for p in allposts]

    return render_template("web_view_user_posts.htmljinja", environment,
                           posts=posts, page_num=page, total_num=total_num,
                           posts_per_page=posts_per_page, user=u)
示例#26
0
def web_view_stream_tag(request, environment, session, username, tagstr,
                        page=1, posts_per_page=15):
    """
    returns the <page> <posts_per_page> posts owned by <username> and tagged
    with <tagstr> as 'posts' and the <username>'s user object as 'user'

    Possible errortype values are:
     *

    May raise the following Exceptions:
     * Exception('NoSuchUser')
     * Exception('InsufficientPrivileges')
     * Exception('InputMakesNoSense')
     * Exception('TagNotFound')
    """

    u = get_user_obj(username, session)

    #identify tag
    res = session.query(tag).filter(tag.tag == tagstr).all()
    if res:
        tag_found = res[0]
        posts = tag_found.posts[(page-1)*posts_per_page:page*posts_per_page]
        posts = [p.downcast() for p in posts]
        posts = sorted(posts, key = lambda p: p.timestamp, reverse=True)
        total_num = len(tag_found.posts)
    else:
        raise Exception("TagNotFound")
    return render_template("web_view_stream_tag.htmljinja", environment,
                           posts=posts, tag=tag_found, show_tags=True, user=u,
                           page_num=page, total_num=total_num,
                           posts_per_page=posts_per_page)
示例#27
0
文件: dynamic.py 项目: ppalucki/shcms
 def refresh_gallery(self):
     from util import render_template
     xml = render_template('gallery2.xml', photos=Photo.all())
     memcache.set("gallery.xml", xml) #@UndefinedVariable
     return webapp2.Response(xml, content_type='application/xml')
 
                    
示例#28
0
 def get(self):
     mode = self.session['ebs_mode']
     settings = BillingSettings.get_settings(mode=mode)
     rendered_response_text = render_template('index.html',
         account_id=settings.account_id,
         ebs_mode=mode,
         default_ebs_secret_key=configuration.DEFAULT_EBS_SECRET_KEY,
         amount=Decimal(str(random.randint(1000, 40000)) + '.' + str(random.randint(10, 100))),
         billing_return_url=configuration.BILLING_RETURN_URL,
         countries=COUNTRIES_TUPLE_MAP,
         description=random.choice(TRANSACTION_DESCRIPTIONS),
         ebs_secure_url=configuration.EBS_SECURE_URL,
         ebs_support_email=configuration.EBS_SUPPORT_EMAIL,
         ebs_support_url=configuration.EBS_SUPPORT_URL,
         reference_number=random.randint(400000, 600000),
         modes=MODES,
         full_name=random.choice(FULL_NAMES),
         city=random.choice(CITIES),
         country_code=random.choice(COUNTRIES_TUPLE_MAP)[0],
         email=random.choice(EMAILS),
         phone_number=random.randint(9800000000, 9899999999),
         postal_address=random.choice(POSTAL_ADDRESSES),
         postal_code=random.randint(400000, 500000),
         state_province=random.choice(STATES),
         ship_full_name=random.choice(FULL_NAMES),
         ship_city=random.choice(CITIES),
         ship_country_code=random.choice(COUNTRIES_TUPLE_MAP)[0],
         ship_email=random.choice(EMAILS),
         ship_phone_number=random.randint(9800000000, 9899999999),
         ship_postal_address=random.choice(POSTAL_ADDRESSES),
         ship_postal_code=random.randint(400000, 500000),
         ship_state_province=random.choice(STATES),
         )
     self.response.out.write(rendered_response_text)
 def get(self):
  extension = self.request.get('extension')
  dbIssues = db.GqlQuery("SELECT * FROM IssueDatabase WHERE extension = '" + extension + "'")
  results = dbIssues.fetch(100)
  theresponse = "<a href='/extension-bugs'>Return to the extension list</a> <a href='/create-bug?extension=" + urllib.quote(extension) + "'>Create a new issue</a><br/>"
  theresponse += "<h1>Issues for <font color='red'>" + extension + "</font></h1>"
  if len(results) > 0:
   theresponse += "<table>"
   theresponse += "<tr><th align='left'>Reporter</th><th align='left'>Summary</th><th></th></tr>"
   for result in results:
    theresponse += "<tr>"
    key = "%s" % result.key()
    if users.is_current_user_admin() and len(result.email) > 5 and result.email.find('@') > 0:
      theresponse += "<td><a href='mailto:" + result.email + "'>" + result.author + "</a></td>"
    else:
      theresponse += "<td>" + result.author + "</td>"
    theresponse +="<td><a href='/view-bug?extension=" + urllib.quote(extension) + "&key=" + key + "'>" + result.title + "</a></td>"
    if users.is_current_user_admin():
     theresponse += "<td>(<a href='/delete-bug-or-comment?extension=" + urllib.quote(extension) + "&action=bug&key=" + key + "'>delete</a>)</td>"
    theresponse += "</tr>"
   theresponse += "</table>"
  else:
   theresponse += "No issues (yet?)."
  template_values = {"title": extension + " Issues",
                     "content": theresponse}
  self.response.out.write(render_template(template_values))
示例#30
0
def admin_reset_password(request, environment, session, username):
    """
    resets  <username>'s password

    Possible errortypes are:
     *
    May raise the following Exceptions:
     *
    """
    class ResetPasswordForm(Form):
        password = TextField("password",
                             [validators.Required()])

    u = get_user_obj(username, session)

    if request.method == 'POST':
        form = ResetPasswordForm(request.form)
        if form.validate():
            u.passwordhash = form.password.data
            session.commit()
            return redirect('/admin/users/view')
    else:
        form = ResetPasswordForm()
        return render_template("admin_reset_password.htmljinja", environment,
                               success=False, user=u, form=form)
示例#31
0
 def get(self):
     util.save_url(self.request, self.response)
     util.fill_app_attrs(self.app, self.request.uri)
     user_agent = self.request.headers['User-Agent']
     view = self.view.type
     self.view.device = device.get_device(user_agent, view)
     self.response.out.write(util.render_template(self.app, self.view))
 def get(self):
  extension = self.request.get('extension')
  author_from_cookie = self.request.cookies.get("author")
  email_from_cookie = self.request.cookies.get("email")
  emailme_from_cookie = self.request.cookies.get("emailme")
  theresponse = "<a href='/bugs?extension=" + urllib.quote(extension) + "'>Return to the list of issues</a><br/>"
  theresponse += "<form action='/bug-process' method='post'><h1>Create a new issue</h1>"
  theresponse += "<input type='hidden' name='extension' value='" + extension + "' size='50'/>"
  theresponse += "<input type='hidden' name='action' value='new' size='50'/>"
  theresponse += "Author <input type='text' name='author' size='50' value='"
  if author_from_cookie != None:
   theresponse += author_from_cookie.replace("'","&quot;")
  theresponse += "'/><br/>"
  theresponse += "E-Mail (only visible to the developer) <input type='text' size='50' name='email' value='"
  if email_from_cookie != None:
   theresponse += email_from_cookie.replace("'","&quot;")
  theresponse += "'><br/>"
  theresponse += "<input type='checkbox' name='emailme'"
  if emailme_from_cookie == None or emailme_from_cookie == "true":
   theresponse += " checked='true'"
  theresponse += " id='emails'><label for='emails'>E-Mail me whenever a new comment is added.</label><br/>"
  theresponse += "Summary <input type='text' name='title' size='55'/><br/>"
  theresponse += "<textarea name='content' cols='50' rows='20'>Google Chrome version (about:version) - \n</textarea><br/>"
  theresponse += "<input type='submit'></form>"
  template_values = {"title": "Create An Issue",
                     "content": theresponse}
  self.response.out.write(render_template(template_values))
 def get(self):
  dbIssues = IssueDatabase()
  bugKey = self.request.get('key')
  extension = self.request.get('extension')
  author_from_cookie = self.request.cookies.get("author")
  email_from_cookie = self.request.cookies.get("email")
  emailme_from_cookie = self.request.cookies.get("emailme")
  theresponse = "<a href='/bugs?extension=" + urllib.quote(extension) + "'>Return to the list</a>"
  result = dbIssues.get(db.Key(bugKey))
  if result:
   if users.is_current_user_admin() and len(result.email) > 5 and result.email.find('@') > 0:
    issue_author = "<a href='mailto:" + result.email + "'>" + result.author + "</a>"
   else:
    issue_author = result.author
   theresponse += "<h1>" + result.title + "</h1>By " + issue_author + ", regarding " + result.extension + "<br/>"
   theresponse += "<pre>" + result.content + "</pre>"
  else:
   theresponse += "<h4>This issue does not exist (anymore?).</h4>"
  dbIssueComments = TechnicalSupportDatabase()
  dbIssueComments = db.GqlQuery("SELECT * FROM TechnicalSupportDatabase " +
                                 "WHERE bugKey = '" + bugKey + "' ORDER BY dateAdded")
  comments = dbIssueComments.fetch(1000)
  if len(comments) > 0:
   theresponse += "<h2>Comments</h2>"
   for comment in comments:
    if users.is_current_user_admin() and len(comment.email) > 5 and comment.email.find('@') > 0:
     theresponse += "<a href='mailto:" + comment.email + "'>" + comment.author + "</a>"
    else:
     theresponse += comment.author
    theresponse += " (" + str(comment.dateAdded) + ") -<br/>"
    theresponse += "<pre>" + comment.content + "</pre><br/>"
    commentKey = "%s" % comment.key()
    if users.is_current_user_admin():
     theresponse += "<a href='/delete-bug-or-comment?extension=" + urllib.quote(extension) + "&action=comment&key=" + commentKey + "&bugKey=" + bugKey + "'>Delete</a><hr/>"
  if result:
   theresponse += "<form action='/bug-process' method='post'><h2>Add comments</h2>"
   theresponse += "<input type='hidden' name='extension' value='" + extension + "' size='50'/>"
   theresponse += "<input type='hidden' name='bugKey' value='" + bugKey + "' size='50'/>"
   theresponse += "<input type='hidden' name='action' value='comment' size='50'/>"
   theresponse += "Author <input type='text' name='author' size='50' value='"
   if author_from_cookie != None:
    theresponse += author_from_cookie.replace("'","&quot;")
   theresponse += "'/><br/>"
   theresponse += "E-Mail (only visible to the developer) <input type='text' size='50' name='email' value='"
   if email_from_cookie != None:
    theresponse += email_from_cookie.replace("'","&quot;")
   theresponse += "'><br/>"
   theresponse += "<input type='checkbox' name='emailme'"
   if emailme_from_cookie == None or emailme_from_cookie == "true":
    theresponse += " checked='true'"
   theresponse += " id='emails'><label for='emails'>E-Mail me whenever a new comment is added.</label><br/>"
   theresponse += "<textarea name='content' cols='50' rows='10'></textarea><br/>"
   theresponse += "<input type='submit'></form>"
  template_values = {"title": "View Issue",
                     "content": theresponse}
  self.response.out.write(render_template(template_values))
示例#34
0
def generate_lists(install_dir):
    # Collect all the lists in use
    list_oftypes = set()
    for uclass in loxi_globals.unified.classes:
        for ofclass in uclass.version_classes.values():
            for m in ofclass.members:
                if isinstance(m, ir.OFDataMember) and \
                        loxi_utils.oftype_is_list(m.oftype):
                    list_oftypes.add(m.oftype)

    for oftype in sorted(list(list_oftypes)):
        cls, e_cls = loxi_utils_legacy.list_name_extract(oftype)
        e_cls = e_cls[:-2]
        e_uclass = loxi_globals.unified.class_by_name(e_cls)
        with template_utils.open_output(install_dir, "loci/src/%s.c" % cls) as out:
            util.render_template(out, "list.c", cls=cls, e_cls=e_cls, e_uclass=e_uclass,
                                 wire_length_get=class_metadata_dict[e_cls].wire_length_get)
            # Append legacy generated code
            c_code_gen.gen_new_function_definitions(out, cls)
示例#35
0
文件: models.py 项目: ppalucki/shcms
 def render_content(self, dynamic=False):
     from util import render_template        
     return render_template(self.template,
                            title = self.title,
                            pages = self.get_all_pages(lang_filter=self.lang),
                            langs = self.get_all_langs(),
                            page = self,
                            link_type = 'dynamic_page' if dynamic else 'static_page',
                            content_link_type = 'dynamic_content' if dynamic else 'static_content'
                            ) 
示例#36
0
 def post(self):
     test_settings = BillingSettings.get_settings(mode=MODE_DEVELOPMENT)
     test_settings.account_id = self.request.get('test_account_id')
     test_settings.secret_key = self.request.get('test_secret_key')
     production_settings = BillingSettings.get_settings(mode=MODE_PRODUCTION)	        
     production_settings.account_id = self.request.get('production_account_id')
     production_settings.secret_key = self.request.get('production_secret_key')
     db.put([test_settings, production_settings])
     response = render_template('settings.html', settings_saved=True, logout_url=users.create_logout_url('/settings/billing/'), test_settings=test_settings, production_settings=production_settings)            
     self.response.out.write(response)
示例#37
0
def default(request, environment, session):
    """
    returns an empty dictionary.

    Possible errortypes are:
     *
    May raise the following Exceptions:
     *
    """
    return render_template("default.htmljinja", environment)
示例#38
0
def web_view_profile(request, environment, session, username):
    """
    Saves a post to <username>'s wurstgulasch.

    Possible errortypes are:
     *
    May raise the following Exceptions:
     *
    """
    u = get_user_obj(username, session)
    return render_template("web_view_profile.htmljinja", environment, user=u)
示例#39
0
 def set_config(self):
     """Creates configuration file for using terraform with openstack"""
     replace_vars = {
                    "CLOUD_NAME": self.cloud_name,
                    "AUTH_URL": self.auth_url,
                    "PROJECT_ID": self.project_id,
                    "PROJECT_NAME": self.project_name,
                    "USER_DOMAIN_NAME": self.user_domain_name,
                    "USERNAME": self.username,
                    "PASSWORD": self.password,
                    "REGION_NAME": self.region_name,
                    "INTERFACE": self.interface,
                    "IDENTITY_API_VERSION": self.identity_api_version,
                    }
     template_file = "clouds.jinja"
     output_file = "clouds.yaml"
     search_path = os.path.abspath(os.path.dirname(__file__)) + "/templates"
     render_template(search_path, template_file, output_file, replace_vars)
     dst_dir = os.path.expanduser('~') + "/.config/openstack/"
     os.makedirs(dst_dir, exist_ok=True)
     shutil.move(output_file, os.path.join(dst_dir, output_file))
示例#40
0
 def get(self):
     from ebs.merchant.api import get_ebs_request_parameters
     from models import BillingTransaction
     mode = self.session['ebs_mode']
     settings = BillingSettings.get_settings(mode=mode)
     dr = self.request.get('DR')
     params = get_ebs_request_parameters(dr, settings.secret_key)
     
     transaction = BillingTransaction()
     transaction.response = str(params)
     transaction.put()
     response = render_template('process.html', mode=mode, params=pformat(params, width=40))
     self.response.out.write(response)
示例#41
0
def web_login(request, environment, session):
    """
    verifies username and password, sets the username attribute of the session
    accordingly.

    Possible errortype values:
     * 'LoginInvalid' if the the login was not successful.
    """
    class LoginForm(Form):
        username = TextField('username', [validators.Required()])
        password = PasswordField('password', [validators.Required()])

    if request.method == "POST":
        form = LoginForm(request.form)
        if form.validate():
            try:
                user_obj = get_user_obj(form.username.data, session)
            # TODO be more specific
            except exc.NoSuchUser:
                return render_template("web_login.htmljinja", environment,
                                       form=form, error="Error: Username \
                                       and password do not match!")
            #TODO hash
            if user_obj.passwordhash == form.password.data:
                http_session = environment['beaker.session']
                http_session['username'] = user_obj.identity.username
                http_session.save()
                return redirect('/')
            else:
                return render_template("web_login.htmljinja", environment,
                                       form=form, error="Error: Username \
                                       and password do not match!")

        else:
            return render_template("web_login.htmljinja", environment,
                                   form=form)
    else:
        form = LoginForm()
        return render_template("web_login.htmljinja", environment, form=form)
示例#42
0
 def email_receipt(self, **kwargs):
     email = self.request.get('email', False)
     key = self.request.get('key', False)
     if key and email:
         t = Transaction2.get(Key(encoded=key))
         its = [LineItem2.get(Key(encoded=i)) for i in t.items]
         d = t.created_on.strftime('%B %d, %Y at %I:%M %p')
         mail.send_mail(sender="Common Thread Register <*****@*****.**>",
                        to=email,
                        subject="Receipt for recent purchase at Common Thread",
                        body=render_template('email_receipt.txt', dict(transaction=t,lineitems=its, transaction_date=d)))
         return dict(valid=True)
     else:
         return dict(valid=False)
示例#43
0
def admin_view_users(request, environment, session):
    """
    returns all user objects known to the system.

    Possible errortypes are:
     *
    May raise the following Exceptions:
     *
    """

    users = session.query(model.user).all()

    return render_template("admin_view_users.htmljinja", environment,
                           users=users)
示例#44
0
def web_view_post_detail(request, environment, session, username, postid):
    """
    Saves a post to <username>'s wurstgulasch.

    Possible errortypes are:
     *
    May raise the following Exceptions:
     *
    """
    u = get_user_obj(username, session)

    p = session.query(model.post).filter(post.post_id == int(postid),).all()[0]
    p = p.downcast()
    return render_template("web_view_post_detail.htmljinja", environment,
                           post=p, user=u, show_tags=True)
示例#45
0
def web_view_stream(request, environment, session, username, page=1,
                    posts_per_page=15):
    """
    returns the <page> <posts_per_page> posts created by <username> as 'posts',
    <username>'s user object as 'user', an empty array if there aren't any.

    Possible errortype values are:
     * 'InputMakesNoSense' if at least one of <page> or <posts_per_page> is
       negative

    May raise the following Exceptions:
     * Exception('NoSuchUser')
     * Exception('InsufficientPrivileges')
    """

    # may raise Exception('NoSuchUser')
    u = get_user_obj(username, session)
    friend_ids = [f.id for f in u.friends]

    # one more time... with subqueries

    # friends' posts
    friendposts = session.query(model.post.id).\
        filter(model.post.owner_id.in_(friend_ids)).subquery()

    # friends' reposts
    friendreposts = session.query(model.post.id).join(model.post_reposters).\
        filter(model.post_reposters.c.identity_id.in_(friend_ids)).subquery()

    # now put it together

    posts = session.query(model.post).\
        filter(or_(model.post.id.in_(friendposts),
                   model.post.id.in_(friendreposts))).\
        order_by(desc(post.timestamp)).\
        offset((page-1)*posts_per_page).limit(posts_per_page).all()

    total_num = session.query(model.post).\
        filter(or_(model.post.id.in_(friendposts),
                   model.post.id.in_(friendreposts))).\
        count()

    posts = [p.downcast() for p in posts]

    return render_template("web_view_stream.htmljinja", environment,
                           posts=posts, user=u, page_num=page, total_num=total_num,
                           posts_per_page=posts_per_page)
 def get(self):
  extensions = ExtensionsDatabase.all()
  theresponse = "<h1>Extensions Bug Database</h1>"
  for extensionResult in extensions:
   extension = extensionResult.name
   extension_link = EXTENSION_GALLERY + extensionResult.eid
   dbIssues = db.GqlQuery("SELECT * FROM IssueDatabase WHERE extension = '" + extension + "'")
   results = dbIssues.fetch(1000)
   extensionsBugs = len(results)
   theresponse += "<a href='/bugs?extension=" + urllib.quote(extension) + "'>" + extension + "</a> (" + str(extensionsBugs) + ") (<a href='" + extension_link + "'>link</a>) (<a href='/complete-changelog?extension=" + extension + "'>Complete Changelog</a>)<br/>"
  if users.is_current_user_admin():
   theresponse += "<br/><br/><form action='/add-extension'>Name - <input type='text' name='name' size='60'/><br/>"
   theresponse += "ID - <input type='text' name='eid' size='60'/><br/>"
   theresponse += "<input type='submit' value='Add Extension'/>"
   theresponse += "</form>"
  template_values = {"title": "Extensions Bug Database",
                     "content": theresponse}
  self.response.out.write(render_template(template_values))
 def get(self):
  extension = self.request.get("extension")
  query = db.GqlQuery("SELECT * FROM ExtensionsDatabase WHERE name = '" + extension + "'")
  theresponse = "<a href='/extension-bugs'>Return to the extension list</a>"
  for result in query.fetch(1):
   theresponse += "<h1>" + extension + " Changelog</h1>"
   if users.is_current_user_admin():
    theresponse += "<form method='post' action='/edit-changelog'>"
    theresponse += "<input type='hidden' name='extension' value='" + extension + "'/>"
    theresponse += "<textarea name='changelog' rows='10' cols='60'>"
   else:
    theresponse += "<pre style='width: 400px'>"
   theresponse += result.changelog
   if users.is_current_user_admin():
    theresponse += "</textarea><br/>"
    theresponse += "<input type='submit' value='Save Changelog'/>"
    theresponse += "</form>"
   else:
    theresponse += "</pre>"
  template_values = {"title": extension + " Changelog",
                     "content": theresponse}
  self.response.out.write(render_template(template_values))
示例#48
0
def generate_message(out, name, version):
    util.render_template(out, 'module.py',
                         ofclasses=modules_by_version[version]['message'],
                         version=version,
                         extra_template='_message_extra.py')
示例#49
0
def generate_meter_band(out, name, version):
    util.render_template(out, 'module.py',
                         ofclasses=modules_by_version[version]['meter_band'],
                         version=version)
示例#50
0
def generate_action_id(out, name, version):
    util.render_template(out, 'module.py',
                         ofclasses=modules_by_version[version]['action_id'],
                         version=version)
示例#51
0
def generate_oxm(out, name, version):
    util.render_template(out, 'module.py',
                         ofclasses=modules_by_version[version]['oxm'],
                         version=version)
示例#52
0
def generate_init_map(install_dir):
    with template_utils.open_output(install_dir, "loci/src/loci_init_map.c") as out:
        util.render_template(out, "loci_init_map.c", classes=of_g.standard_class_order)
示例#53
0
def generate_instruction(out, name, version):
    util.render_template(out, 'module.py',
                         ofclasses=modules_by_version[version]['instruction'],
                         version=version)
示例#54
0
 def render(name, template_name=None, **ctx):
     if template_name is None:
         template_name = os.path.basename(name)
     with template_utils.open_output(install_dir, name) as out:
         util.render_template(out, template_name, **ctx)
示例#55
0
def generate_init(out, name, version):
    util.render_template(out, 'init.py', version=version)
示例#56
0
def generate_pp(out, name, version):
    util.render_template(out, 'pp.py')
示例#57
0
def generate_util(out, name, version):
    util.render_template(out, 'util.py', version=version)
示例#58
0
def generate_common(out, name, version):
    util.render_template(out, 'module.py',
                         ofclasses=modules_by_version[version]['common'],
                         version=version,
                         extra_template='_common_extra.py')
示例#59
0
def generate_const(out, name, version):
    util.render_template(out,
                         'const.py',
                         version=version,
                         enums=of_g.ir[version].enums)
示例#60
0
def generate_class_metadata(install_dir):
    with template_utils.open_output(install_dir, "loci/inc/loci/loci_class_metadata.h") as out:
        util.render_template(out, "loci_class_metadata.h")

    with template_utils.open_output(install_dir, "loci/src/loci_class_metadata.c") as out:
        class_metadata = []
        for uclass in loxi_globals.unified.classes:
            wire_length_get = 'NULL'
            wire_length_set = 'NULL'
            wire_type_get = 'NULL'
            wire_type_set = 'NULL'

            if uclass and not uclass.virtual and uclass.has_type_members:
                wire_type_set = '%s_push_wire_types' % uclass.name

            if uclass.is_message and uclass.name != "of_header":
                wire_length_get = 'of_object_message_wire_length_get'
                wire_length_set = 'of_object_message_wire_length_set'
            elif uclass.is_action:
                wire_length_set = 'of_tlv16_wire_length_set'
                wire_length_get = 'of_tlv16_wire_length_get'
                wire_type_get = 'of_action_wire_object_id_get'
            elif uclass.is_instanceof('of_bsn_vport'):
                wire_length_set = 'of_tlv16_wire_length_set'
                wire_length_get = 'of_tlv16_wire_length_get'
                wire_type_get = 'of_bsn_vport_wire_object_id_get'
            elif uclass.is_action_id:
                wire_length_set = 'of_tlv16_wire_length_set'
                wire_length_get = 'of_tlv16_wire_length_get'
                wire_type_get = 'of_action_id_wire_object_id_get'
            elif uclass.is_instruction:
                wire_length_set = 'of_tlv16_wire_length_set'
                wire_length_get = 'of_tlv16_wire_length_get'
                wire_type_get = 'of_instruction_wire_object_id_get'
            elif uclass.is_instanceof('of_instruction_id'):
                wire_length_set = 'of_tlv16_wire_length_set'
                wire_length_get = 'of_tlv16_wire_length_get'
                wire_type_get = 'of_instruction_id_wire_object_id_get'
            elif uclass.is_instanceof('of_queue_prop'):
                wire_length_set = 'of_tlv16_wire_length_set'
                wire_length_get = 'of_tlv16_wire_length_get'
                wire_type_get = 'of_queue_prop_wire_object_id_get'
            elif uclass.is_instanceof('of_table_feature_prop'):
                wire_length_set = 'of_tlv16_wire_length_set'
                wire_length_get = 'of_tlv16_wire_length_get'
                wire_type_get = 'of_table_feature_prop_wire_object_id_get'
            elif uclass.is_instanceof('of_meter_band'):
                wire_length_set = 'of_tlv16_wire_length_set'
                wire_length_get = 'of_tlv16_wire_length_get'
                wire_type_get = 'of_meter_band_wire_object_id_get'
            elif uclass.is_instanceof('of_hello_elem'):
                wire_length_set = 'of_tlv16_wire_length_set'
                wire_length_get = 'of_tlv16_wire_length_get'
                wire_type_get = 'of_hello_elem_wire_object_id_get'
            elif uclass.is_instanceof('of_bsn_tlv'):
                wire_length_set = 'of_tlv16_wire_length_set'
                wire_length_get = 'of_tlv16_wire_length_get'
                wire_type_get = 'of_bsn_tlv_wire_object_id_get'
            elif uclass.is_oxm:
                wire_length_get = 'of_oxm_wire_length_get'
                wire_type_get = 'of_oxm_wire_object_id_get'
            elif uclass.name == "of_packet_queue":
                wire_length_get = 'of_packet_queue_wire_length_get'
                wire_length_set = 'of_packet_queue_wire_length_set'
            elif uclass.name == "of_meter_stats":
                wire_length_get = 'of_meter_stats_wire_length_get'
                wire_length_set = 'of_meter_stats_wire_length_set'
            elif uclass.name in ["of_group_desc_stats_entry", "of_group_stats_entry",
                   "of_flow_stats_entry", "of_bucket", "of_table_features",
                   "of_bsn_port_counter_stats_entry", "of_bsn_vlan_counter_stats_entry",
                   "of_bsn_gentable_entry_desc_stats_entry", "of_bsn_gentable_entry_stats_entry",
                   "of_bsn_gentable_desc_stats_entry"]:
                wire_length_get = "of_u16_len_wire_length_get"
                wire_length_set = "of_u16_len_wire_length_set"
            elif uclass.name == 'of_match_v3':
                wire_length_set = 'of_tlv16_wire_length_set'
                wire_length_get = 'of_tlv16_wire_length_get'
                wire_type_set = 'of_match_v3_push_wire_types'

            class_metadata.append(ClassMetadata(
                name=uclass.name,
                wire_length_get=wire_length_get,
                wire_length_set=wire_length_set,
                wire_type_get=wire_type_get,
                wire_type_set=wire_type_set))

        class_metadata.extend([
            ClassMetadata(
                name="of_action_header",
                wire_length_set='of_tlv16_wire_length_set',
                wire_length_get='of_tlv16_wire_length_get',
                wire_type_get='of_action_wire_object_id_get',
                wire_type_set='NULL'),
            ClassMetadata(
                name="of_action_id_header",
                wire_length_set='of_tlv16_wire_length_set',
                wire_length_get='of_tlv16_wire_length_get',
                wire_type_get='of_action_id_wire_object_id_get',
                wire_type_set='NULL'),
            ClassMetadata(
                name="of_bsn_vport_header",
                wire_length_set='of_tlv16_wire_length_set',
                wire_length_get='of_tlv16_wire_length_get',
                wire_type_get='of_bsn_vport_wire_object_id_get',
                wire_type_set='NULL'),
            ClassMetadata(
                name="of_instruction_header",
                wire_length_set='of_tlv16_wire_length_set',
                wire_length_get='of_tlv16_wire_length_get',
                wire_type_get='of_instruction_wire_object_id_get',
                wire_type_set='NULL'),
            ClassMetadata(
                name="of_instruction_id_header",
                wire_length_set='of_tlv16_wire_length_set',
                wire_length_get='of_tlv16_wire_length_get',
                wire_type_get='of_instruction_id_wire_object_id_get',
                wire_type_set='NULL'),
            ClassMetadata(
                name="of_queue_prop_header",
                wire_length_set='of_tlv16_wire_length_set',
                wire_length_get='of_tlv16_wire_length_get',
                wire_type_get='of_queue_prop_wire_object_id_get',
                wire_type_set='NULL'),
            ClassMetadata(
                name="of_table_feature_prop_header",
                wire_length_set='of_tlv16_wire_length_set',
                wire_length_get='of_tlv16_wire_length_get',
                wire_type_get='of_table_feature_prop_wire_object_id_get',
                wire_type_set='NULL'),
            ClassMetadata(
                name="of_meter_band_header",
                wire_length_set='of_tlv16_wire_length_set',
                wire_length_get='of_tlv16_wire_length_get',
                wire_type_get='of_meter_band_wire_object_id_get',
                wire_type_set='NULL'),
            ClassMetadata(
                name="of_hello_elem_header",
                wire_length_set='of_tlv16_wire_length_set',
                wire_length_get='of_tlv16_wire_length_get',
                wire_type_get='of_hello_elem_wire_object_id_get',
                wire_type_set='NULL'),
            ClassMetadata(
                name="of_bsn_tlv_header",
                wire_length_set='of_tlv16_wire_length_set',
                wire_length_get='of_tlv16_wire_length_get',
                wire_type_get='of_bsn_tlv_wire_object_id_get',
                wire_type_set='NULL'),
            ClassMetadata(
                name="of_oxm_header",
                wire_length_set='NULL',
                wire_length_get='of_oxm_wire_length_get',
                wire_type_get='of_oxm_wire_object_id_get',
                wire_type_set='NULL'),
        ])

        util.render_template(out, "loci_class_metadata.c", class_metadata=class_metadata)