def db_view(): users = User.query.all() categories = Category.query.order_by('title') add_category_form = AddCategoryForm() add_task_form = AddTaskForm() add_task_form.category_id.choices = [(cat.id, cat.title) for cat in categories] if add_category_form.add_category_submit.data and add_category_form.validate_on_submit(): category = Category(title=add_category_form.title.data, description=add_category_form.description.data) db.session.add(category) db.session.commit() add_category_form = AddCategoryForm() add_task_form = AddTaskForm() categories = Category.query.order_by('title') add_task_form.category_id.choices = [(cat.id, cat.title) for cat in categories] return render_template('db_view.html', title='Database | gtRPG', users=users, categories=categories, add_category_form=add_category_form, add_task_form=add_task_form) elif add_task_form.add_task_submit.data and add_task_form.validate_on_submit(): flash(f'form={add_task_form}') flash(f'{add_task_form.category_id.data}') category = Category.query.get(int(add_task_form.category_id.data)) flash(f'{category}') task = Task(title=add_task_form.title.data, description=add_task_form.description.data, category=category) db.session.add(task) db.session.commit() add_category_form = AddCategoryForm() add_task_form = AddTaskForm() categories = Category.query.order_by('title') add_task_form.category_id.choices = [(cat.id, cat.title) for cat in categories] return render_template('db_view.html', title='Database | gtRPG', users=users, categories=categories, add_category_form=add_category_form, add_task_form=add_task_form) return render_template('db_view.html', title='Database | gtRPG', users=users, categories=categories, add_category_form=add_category_form, add_task_form=add_task_form)
def import_products(request): ProductInfo.objects.all().delete() Product.objects.all().delete() Category.objects.all().delete() Shop.objects.all().delete() dir = os.path.dirname(practice.__file__) file_path = os.path.join(dir, 'shop1.yaml') print(file_path) with open(file_path) as file: shop_dict = yaml.load(file, Loader=yaml.FullLoader) print(shop_dict) shop = shop_dict['shop'] shop_model = Shop(name=shop) shop_model.save() for category in shop_dict['categories']: category_model = Category(id=category['id'], name=category['name']) category_model.save() category_model.shops.add(shop_model) category_model.save() for good in shop_dict['goods']: product = Product( id=good['id'], category_id=good['category'], name=good['name'], ) product.save() product_info = ProductInfo(product=product, price=good['price'], price_rrc=good['price_rrc'], shop=shop_model, quantity=good['quantity']) product_info.save() return HttpResponse("You're looking at question OK")
def test_delete_category(self): category = Category(name='Tech') post = Post(title='test', category=category) db.session.add(category) db.session.add(post) db.session.commit() response = self.client.get(url_for('admin.delete_category', category_id=1), follow_redirects=True) data = response.get_data(as_text=True) assert_not_in('Category deleted.', data) assert_in('405 Method Not Allowed', data) response = self.client.post(url_for('admin.delete_category', category_id=1), follow_redirects=True) data = response.get_data(as_text=True) assert_in('You can not delete the Unknown category.', data) assert_not_in('Category deleted.', data) assert_in('Unknown', data) response = self.client.post(url_for('admin.delete_category', category_id=2), follow_redirects=True) data = response.get_data(as_text=True) assert_in('Category deleted.', data) assert_in('Unknown', data) assert_not_in('Tech', data)
def productadd(request): name = request.POST.get("product-category-name") order = request.POST.get("parentid") cat = request.POST.get("jibie") ztt = request.POST.get("chack") photo = request.FILES.get("upload") if ztt == "增加": path = os.path.join(os.getcwd(), 'static\\upload') pathname = os.path.join(path, photo.name) path1 = default_storage.save(pathname, ContentFile(photo.read())) pathname2 = os.path.join('static/upload', photo.name).replace('\\', '/') c = Category(oname=name, cate=cat, path=pathname2, parentid=order) c.save() if ztt == "禁用": c = Category.objects.get(oname=name) c.zt = 0 c.save() if ztt == "删除": c = Category.objects.get(oname=name) c.delete() return render(request, 'product-category-add.html')
def add(): form_category = AddCategory() form_activity = AddActivity() all_cat = Category.json_all() if form_category.validate_on_submit( ) and form_category.submit_new_category.data: a_category = Category(category=form_category.category_name.data, username_id=current_user.id) Category.save_to_db(a_category) # print(f'well done, we changed {form_category.name} into {form_category.category_name.data}') return render_template('add.html', form_activity=form_activity, form_category=form_category) if form_activity.validate_on_submit( ) and form_activity.submit_new_activity.data: try: a_activity = Activity(name=form_activity.activity_name.data, category_id=form_activity.category_id.data, username_id=current_user.id) # if form_activity.box.data: # a_activity.category_id = form_activity.activity_category_id.data Activity.save_to_db(a_activity) flash(f'well done, we added {form_activity.activity_name.data}') return render_template('add.html', form_activity=form_activity, form_category=form_category, added_activity=True) except: return render_template('add.html', form_activity=form_activity, form_category=form_category, added_activity=True) return render_template('add.html', form_activity=form_activity, form_category=form_category)
def test_set_categories(self): # First we will test that our function is capable to create a new # category object from a new category name (name can't be found in the # table of the ``Category`` table.). expected = Category(name="cat") tested_func = set_categories(["cat"]) self.assertEqual( expected.name, tested_func[0].name, "Function did not return the Category object we were " "looking for.") # Then we will test that if a new post is saved under an existing # category, it is this category that is being attached to the post # instead of creating a category with the same name. expected = add_category("birds") tested_func = set_categories(["birds"]) self.assertEqual( expected, tested_func[0], "Function did not return the Category object we were " "looking for.") # Then will test that an empty string and the "uncategorized" string # are being ignored by the function. tested_func = set_categories(["", "uncategorized"]) self.assertEqual([], tested_func, "Function did not return an empty list.")
def post(self): form = request.form name = form.get("name") subject = form.get("subject") print(form) # 判断name和subject是否为空 if not name or not subject: return error.error_1001() # 同一科目下分类名称不能重复 name_count = Category.Query().filter_by(name=name, subject=subject).count() if name_count: return error.error_1002("此分类已存在") # 判断subject是否合法 if subject not in config.subjects: return error.error_1006() # 提交到数据库 category = Category(form) try: db.session.add(category) db.session.commit() except: return error.error_1003() return error.success()
def register_software(): form = SoftwareForm() if form.validate_on_submit(): software = Software(title=form.title.data, description=form.description.data, officialLink=form.officialLink.data, license=form.license.data, owner=form.owner.data, dateCreation=form.dateCreation.data, author=current_user) db.session.add(software) db.session.flush() category = Category(category=form.category.data, software_id=software.id) db.session.add(category) db.session.flush() tag = Tag(tag=form.tag.data, software_id=software.id) db.session.add(tag) db.session.flush() db.session.commit() flash(_('Você registrou uma nova Aplicação')) return render_template('register_software.html', title=(_('Cadastrar Aplicação')), form=form)
def category_add(type=0): # 商品/服务分类添加 form = CategoryForm() is_flag = True if form.validate_on_submit(): if Category.query.filter_by(name=form.name.data, type=type).first(): is_flag = False flash(u'您输入的分类已存在', 'err') if is_flag == False: return render_template('admin/category_add.html', form=form, type=type) category = Category(name=form.name.data, remarks=form.remarks.data, type=type) oplog = Oplog(user_id=session['user_id'], ip=request.remote_addr, reason=u'添加商品/服务项目分类:%s' % form.name.data) objects = [category, oplog] db.session.add_all(objects) db.session.commit() flash(u'分类添加成功', 'ok') return redirect(url_for('admin.category_add', type=type)) return render_template('admin/category_add.html', form=form, type=type)
def create_post(): if not current_user.is_authenticated: return redirect(url_for("register")) category_id = request.args.get("category_id", None, type=int) form = PostForm() categories = Category.query.order_by("title") if categories.count() == 0: category = Category(title="default") db.session.add(category) db.session.commit() categories = Category.query.order_by("title") form.category_id.choices = [(c.id, c.title) for c in categories] form.category_id.data = (category_id if category_id else categories.first().id) if form.validate_on_submit(): post = Post( title=form.title.data, body=form.body.data, link=form.link.data, url=form.url.data, category_id=form.category_id.data, author=current_user, ) db.session.add(post) db.session.commit() ActivityLog.log_event(current_user, f"Create: {post}") flash("Your post is now live!") return redirect(url_for("index")) return render_template( "create_post.html", greeting_name=greeting_name(), title="Create Post", form=form, )
def test_category_ordering_works(self): c = Category(name='testcat') db.session.add(c) db.session.commit() c = Category.query.get(1) p1 = Painting(name='paint1', category=c, category_order=2, filename='test.jpg') db.session.add(p1) db.session.commit() p2 = Painting(name='paint2', category=c, category_order=1, filename='test.jpg') db.session.add(p2) db.session.commit() response = self.app.get('/paintings/testcat') p1Index = response.data.find(bytes( Painting.query.get(1).name, 'utf-8')) p2Index = response.data.find(bytes( Painting.query.get(2).name, 'utf-8')) self.assertLess(p2Index, p1Index)
def register_source(): form = SourceForm() if form.validate_on_submit(): source = Source(title=form.title.data, city=form.city.data, state=form.state.data, country=form.country.data, description=form.description.data, sphere=form.sphere.data, officialLink=form.officialLink.data, author=current_user) db.session.add(source) db.session.flush() category = Category(category=form.category.data, source_id=source.id) db.session.add(category) db.session.flush() tag = Tag(tag=form.tag.data, source_id=source.id) db.session.add(tag) db.session.flush() db.session.commit() flash(_('Você registrou uma nova Fonte de Dados Abertos')) return render_template('register_source.html', title=(_('Cadastrar Fonte')), form=form)
def add_category(request): name = request.POST['name'] if name == '': return HttpResponseRedirect('/b/edit') color = request.POST['color'] if color == '': color = random.choice(COLORS) column_number = request.POST['column_number'] if column_number == '': column_number = random.randrange(0, 5) else: try: column_number = int(column_number) - 1 except: column_number = random.randrange(0, 5) row_number = request.POST['row_number'] if row_number == '': row_number = -1 else: try: row_number = int(row_number) - 1 except: row_number = -1 category = Category(user=request.user, name=name, column_number=column_number, row_number=row_number, progress_bar_color=color) categories = Category.objects.filter(user=request.user).filter( column_number=column_number) insert_object(categories, category, row_number) return HttpResponseRedirect('/b/edit/')
def category(user): if not user.admin: return {}, 403 if request.method == 'POST': try: name = str(request.data['name']) except KeyError: return {}, 400 category = Category(name=name) category.save() response = jsonify({'id': category.id, 'name': category.name}) response.status_code = 201 return response else: categories = Category.get_all() results = [] for category in categories: obj = {'id': category.id, 'name': category.name} results.append(obj) response = jsonify(results) response.status_code = 200 return response
def test_add_article(self): """添加文章""" category = Category.query.filter_by(category='test').first() if not category: category = Category(category='test') db.session.add(category) tags = [tag for tag in 'test,flask'.split(',')] test_post = Post(body='This is a test post.', title='test', url_name='test-post', category=category, tags='test,flask', timestamp='2018-08-18', draft=False) # for tag in tags: # exist_tag = Tag.query.filter_by(tag=tag).first() # if not exist_tag: # tag = Tag(tag=tag) # db.session.add(tag) db.session.add(test_post) db.session.commit() post = Post.query.filter_by(title='test').first() self.assertIsNotNone(post)
def setUp(self): self.new_category = Category(category_name='category') db.session.add(self.new_category) db.session.commit()
def setUp(self): ''' Set up method that will run before every Test ''' self.new_category = Category()
def add_match(): try: from_request = request.headers.get('Request-From', 'mobile') request_size = request.headers.get('Content-length') # string uid = int(request.headers['Uid']) token_id = request.args.get('token_id') file_name = None saved_path = None if request.form.get('data') is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) item = json.loads(request.form.get('data')) if request.files and len( request.files) > 0 and request.files['image'] is not None: if int( request_size ) <= CONST.UPLOAD_MAX_FILE_SIZE and storage_bl.validate_extension( request.files['image'].filename, CONST.UPLOAD_ALLOWED_EXTENSIONS): file_name, saved_path = storage_bl.handle_upload_file( request.files['image']) else: return response_error(MESSAGE.FILE_TOO_LARGE, CODE.FILE_TOO_LARGE) if token_id is None: contract = contract_bl.get_active_smart_contract() if contract is None: return response_error(MESSAGE.CONTRACT_EMPTY_VERSION, CODE.CONTRACT_EMPTY_VERSION) else: token = Token.find_token_by_id(token_id) if token is None: return response_error(MESSAGE.TOKEN_NOT_FOUND, CODE.TOKEN_NOT_FOUND) token_id = token.id # refresh erc20 contract contract = contract_bl.get_active_smart_contract( contract_type=CONST.CONTRACT_TYPE['ERC20']) if contract is None: return response_error(MESSAGE.CONTRACT_EMPTY_VERSION, CODE.CONTRACT_EMPTY_VERSION) response_json = [] source = None category = None if match_bl.is_validate_match_time(item) == False: return response_error(MESSAGE.MATCH_INVALID_TIME, CODE.MATCH_INVALID_TIME) if "source_id" in item: # TODO: check deleted and approved source = db.session.query(Source).filter( Source.id == int(item['source_id'])).first() elif "source" in item and "name" in item["source"] and "url" in item[ "source"]: source = db.session.query(Source).filter( and_(Source.name == item["source"]["name"], Source.url == item["source"]["url"])).first() if source is None: source = Source(name=item["source"]["name"], url=item["source"]["url"], created_user_id=uid) db.session.add(source) db.session.flush() else: if item['public'] == 1: return response_error(MESSAGE.MATCH_SOURCE_EMPTY, CODE.MATCH_SOURCE_EMPTY) if "category_id" in item: category = db.session.query(Category).filter( Category.id == int(item['category_id'])).first() else: if "category" in item and "name" in item["category"]: category = db.session.query(Category).filter( Category.name == item["category"]["name"]).first() if category is None: category = Category(name=item["category"]["name"], created_user_id=uid) db.session.add(category) db.session.flush() image_url_default = CONST.SOURCE_GC_DOMAIN.format( app.config['GC_STORAGE_BUCKET'], '{}/{}'.format(app.config.get('GC_STORAGE_FOLDER'), app.config.get('GC_DEFAULT_FOLDER')), CONST.IMAGE_NAME_SOURCE_DEFAULT) if source is not None and source.image_url is not None and source.image_url != '': image_url_default = source.image_url match = Match( homeTeamName=item.get('homeTeamName', ''), homeTeamCode=item.get('homeTeamCode', ''), homeTeamFlag=item.get('homeTeamFlag', ''), awayTeamName=item.get('awayTeamName', ''), awayTeamCode=item.get('awayTeamCode', ''), awayTeamFlag=item.get('awayTeamFlag', ''), name=item['name'], public=item['public'], market_fee=int(item.get('market_fee', 0)), date=item['date'], reportTime=item['reportTime'], disputeTime=item['disputeTime'], created_user_id=uid, source_id=None if source is None else source.id, category_id=None if category is None else category.id, grant_permission=int(item.get('grant_permission', 0)), creator_wallet_address=item.get('creator_wallet_address'), outcome_name=item.get('outcome_name'), event_name=item.get('event_name'), image_url=image_url_default) db.session.add(match) db.session.flush() # Add default YES outcome outcome = Outcome(name=CONST.OUTCOME_DEFAULT_NAME, match_id=match.id, contract_id=contract.id, modified_user_id=uid, created_user_id=uid, token_id=token_id, from_request=from_request, approved=CONST.OUTCOME_STATUS['PENDING']) db.session.add(outcome) db.session.flush() match_json = match.to_json() match_json['contract'] = contract.to_json() match_json['source_name'] = None if source is None else source.name match_json[ 'category_name'] = None if category is None else category.name if source is not None: source_json = match_bl.handle_source_data(match.source) match_json["source"] = source_json if category is not None: match_json["category"] = category.to_json() response_json.append(match_json) # Send mail create market send_email_create_market.delay(match.id, uid) db.session.commit() # Handle upload file to Google Storage if file_name is not None and saved_path is not None and storage_bl.check_file_exist( saved_path): upload_file_google_storage.delay(socket.gethostname(), match.id, file_name, saved_path) return response_ok(response_json) except Exception, ex: db.session.rollback() return response_error(ex.message)
def test_posts_have_categories(): cat = Category(title="learnpython") p = Post(title="Why indent?", body="Would not semicolons work?", category=cat) assert p.category == cat
notes= "Laura received a BA in psychology from the University of Washington. She has also completed a course in business French. She reads and writes French." ) db.session.add(e7) e8 = Employee( lastname="Dodsworth", firstname="Anne", notes= "Anne has a BA degree in English from St. Lawrence College. She is fluent in French and German." ) db.session.add(e8) e9 = Employee(lastname="West", firstname="Adam", notes="An old chum.") db.session.add(e9) db.session.commit() c0 = Category(categoryname="Beverages", description="Soft drinks, coffees, teas, beers, and ales") db.session.add(c0) c1 = Category( categoryname="Condiments", description="Sweet and savory sauces, relishes, spreads, and seasonings") db.session.add(c1) c2 = Category(categoryname="Confections", description="Desserts, candies, and sweet breads") db.session.add(c2) c3 = Category(categoryname="Dairy Products", description="Cheeses") db.session.add(c3) c4 = Category(categoryname="Grains/Cereals", description="Breads, crackers, pasta, and cereal") db.session.add(c4) c5 = Category(categoryname="Meat/Poultry", description="Prepared meats") db.session.add(c5)
def test_category(): category = Category(name="Category") assert (category.__hash__() == hash('Category')) assert (category.__repr__() == "<Category Category>") assert (category != 1) assert (category == category)
def category_from_json(json): category = Category() category.name = json['name'] return category
from app import db from app.models import Category, Activity, Date, DateNew, Meal db.create_all() db.session.add(Category(category='test_heroku')) db.session.add(Activity(name='test act', category='test_heroku')) db.session.commit()
from app import db from app.models import User, Judge, Category judges = [ 'Grant Forsberg', 'Stephanie Hansen', 'Thomas Harmon', 'Marcena Hendrix', 'John Huber', 'Marcela Keim', 'Sheryl Lohaus', 'Darryl Lowe', 'Jeff Marcuzzo', 'Craig McDermott', 'Stephanie Shearer', 'Derek Vaughn' ] for judge in judges: j = Judge(name=judge) db.session.add(j) db.session.commit() u = User(username='******', displayname='Christopher', about_me='Bailiff and creator of this site', permissions=2, judge='Marcela Keim') u.set_password('ontheb') db.session.add(u) db.session.commit() categories = [ 'Criminal Traffic', 'Arraignments', 'Trials', 'Jail', 'Probate', 'Civil Motions', 'Civil Call', 'Small Claims', 'Judge', ' General' ] for cat in categories: c = Category(name=cat) db.session.add(c) db.session.commit()
def category(db): _category = Category(name='name1') db.session.add(_category) db.session.commit() return _category
def setUp(self): super().setUp() category = Category(name='test_category') db.session.add(category) db.session.commit()
username='******', email='*****@*****.**', password='******') db.session.add(ian) db.session.add(javier) db.session.add(dean) db.session.add(angela) db.session.add(soonmi) db.session.add(alissa) db.session.add(demo) # CATEGORIES hardware = Category( id=52, title="Hardware", default_pic= "https://images.unsplash.com/photo-1518770660439-4636190af475?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" ) apps = Category( id=332, title="Apps", default_pic= "https://images.unsplash.com/photo-1555774698-0b77e0d5fac6?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" ) printing = Category( id=331, title="3D Printing", default_pic= "https://images.unsplash.com/photo-1582879304171-8041c73bedbd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" ) software = Category(
def create_category(name): c = Category.query.filter_by(name=name).first() if c is None: c = Category(name=name) db.session.add(c) db.session.commit()
def test_slug(self): cat = Category(name="This is a test ---") self.assertEqual(cat.slug, "this-is-a-test")
def category_init_func(row): c = Category(id=row['id'], name=row['nom'], description=row['description']) return c