def test_sites_skus(self): """Erstelle 4 Sites""" s1 = Site(name='Dortmund', region='NRW', adresse='44135') s2 = Site(name='Münster', region='NRW', adresse='48143') s3 = Site(name='Berlin', region='Berlin', adresse='10115') s4 = Site(name='Hamburg', region='Hamburg', adresse='20095') db.session.add_all([s1, s2, s3, s4]) """Erstelle 4 SKU""" sku1 = SKU(name='nike', sortiment='schuhe', gewicht='0.5') sku2 = SKU(name='adidas', sortiment='schuhe', gewicht='0.5') sku3 = SKU(name='puma', sortiment='schuhe', gewicht='0.5') sku4 = SKU(name='erima', sortiment='schuhe', gewicht='0.5') db.session.add_all([sku1, sku2, sku3, sku4]) db.session.commit() """Ordne jeweils einer Site ein SKU zu""" sku1.standort = s1 sku2.standort = s2 sku3.standort = s3 sku4.standort = s4 db.session.commit() """Überprüfe die Einträge per Query""" f1 = Site.query.all() f2 = SKU.query.all() f3 = Site.query.get(1) f3.skus.all()
def create(): db.create_all() for sitename in site_names: site = Site(name=sitename) site.inbuildings_config = InbuildingsConfig(enabled=False, key="") db.session.add(site) for typename in asset_types: asset_type = AssetType(name=typename) db.session.add(asset_type) for pointname in point_types: point_type = PointType(name=pointname) db.session.add(point_type) site = Site.query.filter_by(name=site_names[0]).one() asset_type = AssetType.query.filter_by(name=asset_types[0]).one() asset = Asset(name=test_asset_name, site=site, type=asset_type, health=0, priority=1, notes='') # add one of each point type to dummy unit for pointtype in point_types: point = PointType.query.filter_by(name=pointtype).one() asset_point = AssetPoint(name=pointtype, type=point, asset=asset) asset.points.append(asset_point) db.session.add(asset) db.session.commit() db.session.close()
def addSite(): """addSite sind 3 vordefinierte Sites""" addSite = [('Bochum', 'NRW', '44787'), ('Berlin', 'Berlin', '10115'), ('Köln', 'NRW', '50667')] """Formen aus forms.py""" form1 = SiteaddrandomForm() form2 = SiteForm() """bei bestätigung der form1 wird überprüft ob Bochum bereits besteht, wenn ja Ajax Ausgabe flash()""" if form1.submit1.data and form1.validate_on_submit(): check = Site.query.filter_by(name='Bochum').first() flash('bereits hinzugefügt!') """Hinzufügen der sites nach dem submit""" if check is None: sites = [] for name, region, adresse in addSite: site = Site(name=name, region=region, adresse=adresse) sites.append(site) for site in sites: db.session.add(site) db.session.commit() flash('hinzugefügt!') if form2.submit2.data and form2.validate_on_submit(): site = Site(name=form2.name.data, region=form2.region.data, adresse=form2.adresse.data) """Hinzufügen der Site, die in die Form eingegeben wurde""" db.session.add(site) db.session.commit() flash('Site hinzugefügt') return redirect(url_for('addSite')) return render_template('addSite.html', form1=form1, form2=form2)
def index(): site = Site(1, 2, 3, 4) parsed_sites = site.list_of_full() return render_template("index.html", title="Main", sites=parsed_sites, count_sites=len(parsed_sites))
def test_dao_find_observation_sites_by_name_can_return_multiple_matches( test_db_session): site_1 = Site(id=1, name='Fingrove', observations=True) site_2 = Site(id=2, name='Fingroove', observations=True) site_3 = Site(id=3, name='Fyngrove', observations=True) db.session.add_all([site_1, site_2, site_3]) db.session.commit() result = dao_find_observation_sites_by_name('ngro') assert result == [site_2, site_1, site_3]
def AddRemoveLocation(): form = AddRemoveLocationForm() if form.validate_on_submit(): location_name = form.location_name.data.strip() site_name = form.site_name.data.strip() location = Location.query.filter(Location.ecwid_id == current_user.ecwid_id, Location.name.ilike(location_name)).first() if form.submit1.data is True: if location is not None: if len(site_name) > 0: site = Site.query.filter(Site.loc_id == location.id, Site.name.ilike(site_name)).first() if site is None: site = Site(name = site_name, loc_id = location.id) db.session.add(site) db.session.commit() flash('Объект {} создан'.format(site_name)) else: flash('Такой объект уже существует') else: flash('Такой проект уже существует') else: location = Location(name = location_name, ecwid_id = current_user.ecwid_id) db.session.add(location) db.session.commit() flash('Проект {} создан'.format(location_name)) if len(site_name) > 0: site = Site(name = site_name, loc_id = location.id) db.session.add(site) db.session.commit() flash('Объект {} создан'.format(location_name)) elif form.submit2.data is True: if location is not None: if len(site_name) == 0: Site.query.filter(Site.loc_id == location.id).delete() db.session.delete(location) db.session.commit() flash('Проект {} удален'.format(location_name)) else: site = Site.query.filter(Site.loc_id == location.id, Site.name.ilike(site_name)).first() if site is not None: db.session.delete(site) db.session.commit() flash('Объект {} удален'.format(site_name)) else: flash('Такой объект не существует') else: flash('Такого проекта не существует') else: for error in form.location_name.errors: flash(error) return redirect(url_for('main.ShowSettings'))
def folder(page=1): parent_id = 0 top = 0 success = True if request.method == 'POST': sub_folder = request.form.get('folder') parent_directory = request.form.get('parent_directory', '') # 验证目录 if sub_folder is None: return custom_response(False, gettext("Directory name isn't empty!")) sub_folder = parse.unquote(sub_folder) if not re.match(r'^[0-9a-zA-Z_]+$', sub_folder): return custom_response( False, gettext("Directory name only character or underline!")) if Directory.query.filter_by(site_id=Site.master_site_id(current_user), name=sub_folder).first(): return custom_response(False, gettext("Directory name is already exist!")) if parent_directory != '': directories = parent_directory.split('/') # pop last item last_directory_name = directories.pop() last_directory = Directory.query.filter_by( site_id=Site.master_site_id(current_user), name=last_directory_name).first() parent_id = last_directory.id top = 1 try: directory = Directory(name=sub_folder, master_uid=Master.master_uid(), site_id=Site.master_site_id(current_user), user_id=current_user.id, parent_id=parent_id, top=top) db.session.add(directory) db.session.commit() except Exception as ex: success = False return status_response(success)
def addsite(): title = "GecMonitor | Add a Site" site = Site() form = AddSiteForm() if request.method == 'POST' and form.validate(): site_name = form.site_name.data gt_global_id = form.gt_global_id.data new_site = Site(site_name=site_name, gt_global_id=gt_global_id) current_user.sites.append(new_site) db.session.add(new_site) db.session.commit() flash(f"{site_name} has been added to your sites!") return redirect(url_for("mysites")) return render_template("add_site.html", title=title, site=site, form=form)
def test_dao_get_all_sites(test_db_session): site_g = Site(id=5, name='Golf') obs_site_f = Site(id=1, name='Foxtrot', observations=True) obs_site_a = Site(id=17, name='Alpha', observations=True) site_k = Site(id=10, name='Kilo') db.session.add_all([site_g, obs_site_f, obs_site_a, site_k]) db.session.commit() result = dao_get_all_sites() assert len(result) == 4 assert result[0].name == 'Alpha' assert result[1].name == 'Foxtrot' assert result[2].name == 'Golf' assert result[3].name == 'Kilo'
def get_sighting(areaid): import string area = Area.query.filter_by(id=areaid).first() if area is None : return make_response(jsonify({ 'list' : [] })), 200 sites = [] for site in Site.get_all(): if area.contains(site): sites.append(str(site.id)) def generate_random_data(num_rows): import random latitude = 51.51451110408478 longitude = -0.12620388576521444 result = [] for _ in range(num_rows): dec_lat = random.random()/10 dec_lon = random.random()/10 result.append({'lat' : latitude + dec_lat, 'lng' : longitude + dec_lon}) return result results = [] if (len(sites) > 0): for row in db.session.execute('select * from get_gender_crossfilter(ARRAY[' + ','.join(sites) + '])'): results.append(({ 'geos': generate_random_data(5), 'gender' : row['__gender'], 'age_range' : row['__age_range'], 'timestamp' : row['__sighting_date'], 'count' : row['__count'] })) return make_response(jsonify({ 'list' : results })), 200
def test_all_site_forecasts_shows_each_site_name_and_links_to_its_page( test_client, test_db_session): site_1 = Site(id=1, name='Farley Down') site_2 = Site(id=2, name='Little Borwood', observations=True) db.session.add_all([site_1, site_2]) db.session.commit() response = test_client.get(url_for('main.all_site_forecasts')) page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser') link_one = page.find('a', string='Farley Down') assert link_one['href'] == url_for('main.site_forecast', site_id=1) link_two = page.find('a', string='Little Borwood') assert link_two['href'] == url_for('main.site_forecast', site_id=2)
def show_categories(page=1): per_page = request.args.get('per_page', 10, type=int) # 获取当前官网 current_site = Site.current_site(master_uid=Master.master_uid()) builder = Category.query.filter_by(site_id=current_site.id) total_count = builder.count() categories = Category.always_category( site_id=current_site.id, language_id=current_site.default_language, path=0, page=1, per_page=per_page) paginated_categories = [] for cate in categories: category = { 'id': cate.id, 'name': cate.name, 'icon': Asset.query.get(cate.icon_id) if cate.icon_id else None, 'sort_order': cate.sort_order, 'status': cate.status } paginated_categories.append(category) pagination = Pagination(query=None, page=1, per_page=per_page, total=total_count, items=None) return render_template('admin/categories/show_list.html', paginated_categories=paginated_categories, pagination=pagination)
def get_sites(): # get all the areas sites = Site.get_all() results = [] for site in sites: results.append(site.serialise()) return make_response(jsonify({ 'list' : results })), 200
def site(): '''机房设置''' role_permission = getattr(Permission, current_user.role) site_form = SiteForm() sidebar = copy.deepcopy(start_sidebar) thead = copy.deepcopy(start_thead) sidebar = init_sidebar(sidebar, now, 'edititem') search_value = '' if request.method == "GET": search_value = request.args.get('search', '') checkbox = request.args.getlist('hidden') or request.args.get( 'hiddens', '') if search_value: thead = init_checkbox(thead, checkbox) sidebar = init_sidebar(sidebar, now, "edititem") page = int(request.args.get('page', 1)) result = search(Site, 'site', search_value) result = result.search_return() if result: pagination = result.paginate(page, 100, False) items = pagination.items return render_template('cmdb/item.html', sidebar=sidebar, item_form=client_form, search_value=search_value, checkbox=str(checkbox), thead=thead, pagination=pagination, endpoint=endpoint, items=items) if request.method == "POST" and \ role_permission >= Permission.ALTER: sidebar = init_sidebar(sidebar, now, "additem") if site_form.validate_on_submit(): site = Site(site=site_form.site.data, isp=site_form.isp.data, location=site_form.location.data, address=site_form.address.data, contact=site_form.contact.data, dns=site_form.dns.data, remark=site_form.remark.data) add_sql = edit(current_user.username, site, "site") add_sql.run('add') flash(u'机房添加成功') else: for thead in start_thead: key = thead[2] if site_form.errors.get(key, None): flash(site_form.errors[key][0]) break return render_template('cmdb/item.html', sidebar=sidebar, item_form=site_form, search_value=search_value, thead=thead)
def include_common_data(): """注入共用的变量""" # 所属的官网 current_site = Site.current_site(master_uid=Master.master_uid()) return { 'current_site': current_site, 'site_languages': current_site.languages }
def create_site(): api_key = request.headers.get('Authorization') user = User.query.filter_by(api_key=api_key).first() data, errors = site_schema.load(request.get_json()) if errors: return jsonify(errors), 400 db.session.add(Site(**data, user=user)) db.session.commit() return jsonify({"message": "site created"}), 201
def site(): '''机房设置''' role_Permission = getattr(Permission, current_user.role) site_form = SiteForm() sidebarclass = init__sidebar('edititem') if request.method == "POST" and \ role_Permission >= Permission.ALTER_REPLY: sidebarclass = init__sidebar('additem') if site_form.validate_on_submit(): site = Site(site=site_form.site.data, isp=site_form.isp.data, location=site_form.location.data, address=site_form.address.data, contact=site_form.contact.data, dns=site_form.dns.data, remark=site_form.remark.data) db.session.add(site) db.session.commit() value = ("site:%s isp:%s location:%s address:%s" "contact:%s dns:%s remark:%s") % ( site.site, site.isp, site.location, site.address, site.contact, site.dns, site.remark) record_sql(current_user.username, u"创建", u"机房", site.id, "site", value) flash(u'机房添加成功') else: for key in site_form.errors.keys(): flash(site_form.errors[key][0]) if request.method == "GET": search = request.args.get('search', '') if search: # 搜索 page = int(request.args.get('page', 1)) sidebarclass = init__sidebar('edititem') res = search_res(Site, 'site', search) if res: pagination = res.paginate(page, 100, False) items = pagination.items return render_template('cmdb/item.html', titles=titles, thead=thead, endpoint=endpoint, del_page=del_page, change_page=change_page, item_form=site_form, sidebarclass=sidebarclass, pagination=pagination, search_value=search, items=items) return render_template('cmdb/item.html', titles=titles, item_form=site_form, sidebarclass=sidebarclass)
def edit_category(id): # 获取当前官网 current_site = Site.current_site(master_uid=Master.master_uid()) site_languages = current_site.support_languages category = Category.query.get_or_404(id) form = CategoryForm() if form.validate_on_submit(): category.top = form.top.data category.parent_id = form.parent_id.data category.icon_id = form.icon.data category.cover_id = form.cover.data category.sort_order = form.sort_order.data category.status = form.status.data # update category description for cate_desc in category.category_descriptions: lang_id = cate_desc.language_id cate_desc.name = request.form.get( 'category_description[%d][name]' % lang_id) cate_desc.description = request.form.get( 'category_description[%d][description]' % lang_id) db.session.commit() # rebuild category path Category.repair_categories(category.parent_id) flash(gettext('Edit category is ok!'), 'success') return redirect(url_for('.show_categories')) mode = 'edit' form.top.data = category.top form.parent_id.data = category.parent_id form.icon.data = category.icon_id form.cover.data = category.cover_id form.sort_order.data = category.sort_order form.status.data = category.status paginated_categories = Category.always_category( site_id=current_site.id, language_id=current_site.default_language, path=0, page=1, per_page=100) return render_template('admin/categories/create_and_edit.html', form=form, category=category, mode=mode, languages=site_languages, all_descriptions=category.all_descriptions(), paginated_categories=paginated_categories)
def parsed(): error = None url = request.form['url'] parsed_url = parsing_url(url) site = Site(parsed_url['url'], parsed_url['title'], parsed_url['keywords'], parsed_url['description']) if validators.url(url) is not True: error = "Not a valid URL" elif site.search(url) == False: error = 'The URL is already in the database' parsed_url = None else: site.add_url() flash(error) return render_template('parsed.html', url=url, parsed_url=parsed_url, title="Parsed", error=error)
def sites(): categories = Category.query.all() sites = Site.query.all() if not current_user.is_admin: return render_template("sites.html", sites=sites, categories=categories, header="Сайты") add_form = AddSiteForm() if request.method == 'POST': site_manager = None if request.form['name'] != "": site_name = request.form["name"] if request.form['url'] != "": site_url = request.form["url"] if request.form['manager'] != "": site_manager = request.form["manager"] if Site.query.filter(Site.name == site_name).first() != None: err = "Такой сайт уже есть" return err elif Site.query.filter(Site.url == site_url).first() != None: err = "Такой сайт уже есть" return err elif User.query.filter(User.is_manage == True and User.login == site_manager).first() == None: err = "Пользователь не найден" return err else: site = Site() site.name = site_name site.url = site_url if site_manager != None: site.manager_id = User.query.filter( User.is_manage == True and User.login == site_manager).first().id db.session.add(site) db.session.commit() return redirect(url_for("sites")) return render_template("sites.html", sites=sites, categories=categories, add_form=add_form, header="Сайты")
def create_site(): selected_template = request.args.get('template') form = get_site_form(selected_template) if form.validate_on_submit(): site_name = form.name.data template_name = form.template.data # The used template should be copied to the data backend # to ensure changes on the template file don't interfere # with the uncommitted site. # Upcoming edits are soley done on this stored template content with open(os.path.join(TEMPLATE_DIR, template_name), 'rb') as fd: template_content = base64.b64encode(gzip.compress( fd.read())).decode('ascii') template_vars = get_template_variables(template_name) site = Site( name=site_name, template_name=template_name, template_content=template_content, template_parameters=get_template_parameters(form, template_vars), ) selected_deployment = get_selected_deployment() if selected_deployment: site.deployment = selected_deployment db.session.add(site) db.session.commit() flash('Site {} created'.format(form.name.data)) audit_log('created site:', site_name, '|', 'template:', template_name, '|', 'data:', site.template_parameters) return redirect(url_for('edit_site', site_name=site_name)) else: if form.errors: flash(form.errors) form.process() # needed to send the "selected" option to html context = get_context() return _render_template('generic_form.html', title='New Site', form=form, **context)
def on_message(self, message): message=ast.literal_eval(message) print(message) coordonates={} if message.get('action')=='get_position': coordonates=self.getPosition() elif message.get('action')=='start_persiste': print("start persisting....") self.site_name=str(message.get('site_name')) self.capture_type=str(message.get('type')) self.description=str(message.get('description')) self.site_number = str(int(time.time())) + str(random.randrange(1, 99)) _name=self.site_name _description=self.description _type=self.capture_type _site_number=self.site_number monSite=Site(name=_name,description=_description,site_number=_site_number,type=_type) monSite.save() self.persit = True elif message.get('action')=='stop_persiste': self.persit=False
def obs_site(test_db_session): """Inserts a site with observations into the database and returns it""" site = Site( id=100, name='Silverley', latitude=51.148, longitude=0.661, elevation=10, region='se', unitary_auth_area='Kent', observations=True, ) db.session.add(site) db.session.commit() return site
def site(test_db_session): """Inserts a site without into the database and returns it""" site = Site( id=99, name='Lochaven', latitude=56.503, longitude=-4.332, elevation=995, region='he', unitary_auth_area='Highland', observations=False ) db.session.add(site) db.session.commit() return site
def report_update(report_id, report_update_id): report = Report.query.get_or_404(report_id) report_update = ReportUpdate.query.get_or_404(report_update_id) site_updates = report_update.site_updates site_update_ids = [site_update.id for site_update in site_updates] sites_list = [[site_update.site_id, site_update.site.gt_global_id] for site_update in site_updates] context = { 'title': f'GecMonitor | {report.report_name}: {report_update.scraped_on} Report', 'report': report, 'report_update': report_update, 'Site': Site(), 'site_updates': site_updates, 'dt': dt } return render_template('report_update.html', **context)
def flupload(): saved_asset_ids = [] sub_folder = str(time.strftime('%y%m%d')) directory_id = 0 directory = _pop_last_directory() if directory: current_directory = Directory.query.filter_by(name=directory).first() directory_id = current_directory.id # for key, file in request.files.iteritems(): for f in request.files.getlist('file'): upload_name = f.filename # start to save name_prefix = 'admin' + str(time.time()) name_prefix = hashlib.md5(name_prefix.encode('utf-8')).hexdigest()[:15] filename = uploader.save(f, folder=sub_folder, name=name_prefix + '.') storage_filepath = uploader.path(filename) current_app.logger.warning('upload filename: %s, filepath: %s' % (filename, storage_filepath)) # get info of upload image im = Image.open(storage_filepath) size = os.path.getsize(storage_filepath) / 1024 # k new_asset = Asset(master_uid=Master.master_uid(), site_id=Site.master_site_id(current_user), user_id=current_user.id, filepath=filename, filename=upload_name, directory_id=directory_id, width=im.width, height=im.height, size=size) db.session.add(new_asset) db.session.commit() saved_asset_ids.append(new_asset.id) return jsonify({'status': 200, 'ids': saved_asset_ids})
def main(): db.drop_all() db.create_all() data = yaml.safe_load(open('data.yaml')) basic_user = Role(name="basic_user") db.session.add(basic_user) user_roles = {} for role in data['roles']: r = Role(name=role['rolename']) if 'permissions' in role: r.permissions = role['permissions'] db.session.add(r) for user in role['users']: user_roles[user] = r db.session.commit() for user in data['users']: username = user['username'] u = User( username=username, firstname=user['firstname'], lastname=user['lastname'], email=user['email'], password_hash=generate_password_hash(user['password']), role=basic_user, ) if username in user_roles: u.role = user_roles[username] db.session.add(u) print(u, u.role) db.session.commit() for deployment in data['deployments']: d = Deployment(name=deployment['name']) db.session.add(d) for site in deployment['sites']: s = Site(name=site, deployment=d) print(s) db.session.add(s) print(d) db.session.commit()
def show_brands(page=1): per_page = request.args.get('per_page', 10, type=int) status = request.args.get('status', 0, type=int) # 获取所属站点 current_site_id = Site.master_site_id(current_user) builder = Brand.query.filter_by(site_id=current_site_id) if status: builder = builder.filter_by(status=status) paginated_brands = builder.order_by(Brand.created_at.desc()).paginate( page, per_page) if paginated_brands: paginated_brands.offset_start = 1 if page == 1 else (page - 1) * per_page paginated_brands.offset_end = paginated_brands.offset_start + len( paginated_brands.items) - 1 return render_template('admin/brands/show_list.html', paginated_brands=paginated_brands)
def group(group_id): form = SiteForm() current_group = Group.query.get(group_id) if form.validate_on_submit(): site = Site(link=form.link.data, description=form.description.data, author=current_user, category=current_group) db.session.add(site) db.session.commit() flash('Your site was added!') return redirect(url_for('group', group_id=group_id)) group = Group.query.get(group_id) siteList = group.sites sites = [] for s in siteList: sites.append(s) return render_template('group.html', title=group.name, form=form, group=group, sites=sites)
def test_dao_get_all_sites_with_observations_returns_obs_sites( test_db_session): site_g = Site(id=5, name='Golf') obs_site_f = Site(id=1, name='Foxtrot', observations=True) site_i = Site(id=73, name='India', observations=False) obs_site_a = Site(id=17, name='Alpha', observations=True) obs_site_m = Site(id=56, name='Mike', observations=True) site_k = Site(id=10, name='Kilo') db.session.add_all( [site_g, obs_site_f, site_i, obs_site_a, obs_site_m, site_k]) db.session.commit() result = dao_get_all_sites_with_observations() assert len(result) == 3 assert result[0].name == 'Alpha' assert result[1].name == 'Foxtrot' assert result[2].name == 'Mike'
def save_data(self): for row in self.rows_list: try: site = Site() cont = 'no' if self.status_col and row[self.status_col]: if self.status_col == 'Closed': if row[self.status_col] != '': cont = 'yes' else: for retired_name in WikiEnergyTable.inactive_colnames: if retired_name in row[self.status_col]: cont = 'yes' if cont =='yes': continue site.name = row[self.name_col] if self.name_col else '' if not self.type_id: if self.type_col and row[self.type_col]: site.type_id = site.choose_type_id(row[self.type_col]) elif self.more_type_info_cols is not None: for col in self.more_type_info_cols: if site.choose_type_id(row[col]) != 1: site.type_id = site.choose_type_id(row[col]) break else: site.type_id = 1 else: site.type_id = 1 else: site.type_id = self.type_id site.subtype_id = site.choose_subtype_id(row[self.subtype_col]) if self.subtype_col and row[self.subtype_col] else 1 site.capacity = re.sub("[MW]", "", row[self.capacity_col]) if(self.capacity_col and row[self.capacity_col]) else '' site.latitude = None site.longitude = None if self.coordinates_col and row[self.coordinates_col]: if self.coordinates_col in WikiEnergyTable.uk_grid_coordinates_colnames: coords = OSGB36toWGS84.osgb36_to_wgs84(row[self.coordinates_col]) site.latitude = coords[1] site.longitude = coords[0] else: site.latitude = row[self.coordinates_col].split(';')[0] site.longitude = row[self.coordinates_col].split(';')[1].replace(' ', '') site.owner_name = row[self.owner_col] if self.owner_col and row[self.owner_col] else '' site.url = row['url'] if row['url'] else '' site.country_id = self.country_id site.data_source_id = self.source_id db.session.add(site) except: logging.exception('Exception hit in save_data() on ' + 'name') db.session.commit()