def api_interfaces(*, page='1'): #获取API信息 page_index = get_page_index(page) num = yield from Interface.findNumber('count(id)') p = Page(num, page_index) if num == 0: return dict(page=p, Interfaces=()) interfaces = yield from Interface.findAll(orderBy='created_at desc', limit=(p.offset, p.limit)) return dict(page=p, ineterfaces=interfaces)
def api_create_interface(request, *, name, summary, content): #只有管理员可以写API check_admin(request) #name, summary, content不能为空 if not name or not name.strip(): raise APIValueError('name', 'name cannot be empty') if not summary or not summary.strip(): raise APIValueError('summart', 'summary cannot be empty') if not content or not content.strip(): raise APIValueError('content', 'content cannot be empty') #根据传入的信息,构建一条API数据 #logging.info("user id --------------id:%s,name:%s,image:%s,summary:%s"%(request.__user__.id, request.__user__.name, request.__user__.image, request.__user__.summary)) interface = Interface(user_id=request.__user__.id, user_name=request.__user__.name, user_image=request.__user__.image, name=name.strip(), summary=summary.strip(), content=content.strip()) #interface = Interface(interface_id=request.__user__.id, interface_name=request.__user__.name, interface_image=request.__user__.image, name=name.strip(), summary=summary.strip(), content=content.strip()) #保存 yield from interface.save() logging.info("save interface %s"%summary) return interface
def index(*, page='1'): #获取到要展示的API页数是第几页 page_index = get_page_index(page) #查找API表里的条目数 num = yield from Interface.findNumber('count(id)') #通过Page类计算当前页的相关信息 page = Page(num, page_index) #如果表里没有条目,则不需要 if num == 0: interfaces = [] else: #根据计算出来的offset(取的初始条目index)和limit(取的条数),来取出条目 interfaces = yield from Interface.findAll(orderBy='created_at desc', limit=(page.offset, page.limit)) #返回给浏览器 return { '__template__': 'interfaces.html', 'page': page, 'interfaces': interfaces }
def save_interfaces(self, db_device, parsed_device_config): def _save_acl(db_interface): def save(acl_name): try: acl = ACL(interface=db_interface, name=acl_name, extended=parsed_device_config['ACLs'][acl_name]['Extended']) except KeyError: pass # access-group enabled on interface but access-list not exist else: acl.save() rule_mass = [] for nbr, rule_str in enumerate(parsed_device_config['ACLs'][acl_name]['Rules'].split('|')): if rule_str: dic_rule = parse_rule(rule_str) if dic_rule: rule = ACLRule(line_number=nbr, permit=dic_rule['Permit'], protocol=dic_rule['Protocol'], ip_source=dic_rule['IP_src'], ip_src_mask=dic_rule['Src_mask'], src_port=dic_rule['Src_port'], src_operand=dic_rule['Src_operand'], ip_destination=dic_rule['IP_dst'], ip_dst_mask=dic_rule['Dst_mask'], dst_port=dic_rule['Dst_port'], dst_operand=dic_rule['Dst_operand'], acl=acl, rule_str=rule_str) rule_mass.append(rule) ACLRule.objects.bulk_create(rule_mass) if db_interface.access_group_in: acl_name = db_interface.access_group_in save(acl_name) if db_interface.access_group_out: acl_name = db_interface.access_group_out save(acl_name) for interface_name, interface_options in parsed_device_config['interfaces'].items(): db_interface = Interface(name=interface_name, description=interface_options.get('Description'), ip_address=interface_options.get('IP'), mode_port=interface_options.get('Mode'), allowed_vlan=interface_options.get('AllowedVlan'), trunk_encapsulation=interface_options.get('TEncapsulation'), access_vlan=interface_options.get('AccessVlan'), access_group_in=interface_options.get('AccessGroupIn'), access_group_out=interface_options.get('AccessGroupOut'), name_if=interface_options.get('Name_If'), security_level=interface_options.get('SecurityLevel'), device=db_device) if not interface_options.get('Shutdown'): db_interface.shutdown = False else: db_interface.shutdown = True if not interface_options.get('noSwitchport'): db_interface.no_switchport = False else: db_interface.no_switchport = True db_interface.save() if db_interface.access_group_in or db_interface.access_group_out: _save_acl(db_interface)
def api_delete_interface(id, request): #删除一个API logging.info("删除API的APIID为:%s" % id) #检查权限 check_admin(request) #查询评论id是否有对应的评论 b = yield from Interface.find(id) #没有抛出异常 if b is None: raise APIResourceNotFoundError('Comment') yield from b.remove() return dict(id=id)
def parse_interface(item, logical_system=None): iface = Interface() iface.name = item['name'] iface.description = item.get('description') iface.vlantagging = 'vlan-tagging' in item or 'flexible-vlan-tagging' in item iface.unitdict = [parse_unit(u, logical_system) for u in item.get('unit', [])] iface.bundle = find_first('bundle', item) or None iface.tunneldict = [ { 'source': find('tunnel.source', u), 'destination': find('tunnel.destination', u) } for u in item.get('unit', []) if 'tunnel' in u ] return iface
def get_interface(id): #根据APIid查询该API信息 interface = yield from Interface.find(id) #根据APIid查询该API评论 comments = yield from Comment.findAll('interface_id=?', [id], orderBy='created_at desc') #markdown2是个扩展模块,把API正文和评论套入markdown2中 for c in comments: c.html_content = text2html(c.content) interface.html_content = markdown2.markdown(interface.content) #返回页面 return { '__template__': 'interface.html', 'interface': interface, 'comments': comments }
def interface_response(name): #格局APIid获取API返回 interfaces = yield from Interface.findAll('name=?', [name], orderBy='created_at desc') #interface = yield from Interface.findByCondition(name) #for interface in interfaces: # return interface.content #interface = None #for interface in interfaces: if len(interfaces) == 1: interface = interfaces[0] elif len(interfaces) > 1: raise APIValueError('name', 'The API name is not unique') else: raise APIValueError('name', 'Can\'t find %s API' % name) interface.content_type = 'application/json' return interface.content
def interface_generate(interface_card_uid: str, max_interfaces: int) -> None: ic = InterfaceCard.nodes.get(uid=interface_card_uid) nm = ic.network_module.get() switch = nm.switch.get() if len(ic.interfaces.all()): print('\tUsing existing Interface(s) for %s:%d\%d' % (switch.hostname, nm.position, ic.position)) else: print('\tCreating new Interface(s) for %s:%d\%d' % (switch.hostname, nm.position, ic.position)) for position in range(0, random.randint(1, max_interfaces)): # noinspection PyTypeChecker interface = Interface.create_or_update( {'position': position}, relationship=ic.interfaces)[0] print('\t\tUpserted Interface %s:%d\%d\%d' % (switch.hostname, nm.position, ic.position, interface.position))
def api_create_comment(id, request, *, content): #对某个API发表评论 user = request.__user__ #评论必须为登录状态下 if user is None: raise APIPermissionError('content') #评论不能为空 if not content or not content.strip(): raise APIValueError('content') #查询APIid是否有对应API interface = yield from Interface.find(id) if interface is None: raise APIResourceNotFoundError('Interface') #构建一条评论数据 comment = Comment(interface_id=interface.id, user_id=user.id, user_name=user.name, user_image=user.image, content=content.strip()) #保存到评论里 yield from comment.save() return comment
def api_modify_interface(request, *, id, name, summary, content): #修改一个API logging.info("修改的APIID为:%s", id) #name, summary, content不能为空 if not name or not name.strip(): raise APIValueError('name', 'name cannot be empty') if not summary or not summary.strip(): raise APIValueError('summary', 'summary cannot be empty') if not content or not content.strip(): raise APIValueError('content', 'content cannot be empty') #获取指定id的API数据 interface = yield from Interface.find(id) interface.name = name interface.summary = summary interface.content = content #保存 yield from interface.update() return interface
def addinterface(model_id): if not session.get("logged_in"): return redirect(url_for("login")) add_interface = InterfaceForm() submit = SubmitForm() if submit.validate_on_submit(): add = Interface(interface_name=add_interface.interface_name.data, model_id=model_id, interface_url=add_interface.interface_url.data, interface_method=add_interface.interface_method.data, request_exam=add_interface.request_exam.data, response_exam=add_interface.response_exam.data) db.session.add(add) db.session.commit() return redirect(url_for("interface", model_id=model_id)) return render_template("addinterface.html", add_interface=add_interface, model_id=model_id, submit=submit)
def parse(self, nodeTree, physicalInterfaces=[]): host_name = get_hostname(ElementParser(nodeTree)) interfaceNodes = [ interface for i in ElementParser(nodeTree).all("interfaces") if i.parent().tag() in ['configuration'] for interface in i.all("interface") ] interfaces = [] for node in interfaceNodes: interface = Interface() interface.name = node.first("name").text() if physicalInterfaces: if not interface.name in physicalInterfaces: logger.warn("Interface {0} is configured but not found in {1}".format(interface.name, host_name)) continue else: physicalInterfaces.remove(interface.name) interface.vlantagging = len(node.all("vlan-tagging")) > 0 interface.bundle = node.first("bundle").text() interface.description = node.first("description").text() #TODO: tunnel dict..? Does it make sense when source/dest is empty? interface.tunneldict.append({ 'source': node.first("source").text(), 'destination': node.first("destination").text(), }) #Units interface.unitdict = [ self._unit(u) for u in node.all("unit") ] interfaces.append(interface) for iface in physicalInterfaces: interface = Interface() interface.name = iface interfaces.append(interface) return interfaces
def api_get_interface(*, id): #获取某个API的信息 interface = yield from Interface.find(id) return interface
def parse_interface(data): iface = Interface() iface.name = 'et{}'.format(data['name']) iface.description = data.get('description') return iface
def new_interface(self, name): interface = Interface() interface.name = name return interface