def test_list(): c1 = Concept('_666') c2 = Concept('_999') l1 = Label('foo', 'en') l2 = Label('bar', 'de') lines = txt.list_concepts([c1, c2]) lines = ''.join(lines) assert lines == '_666\n_999\n' c1.pref_labels.append(l1) lines = txt.list_concepts([c1, c2]) lines = ''.join(lines) assert lines == 'foo\n_999\n' c1.alt_labels.append(l2) lines = txt.list_concepts([c1, c2]) lines = ''.join(lines) assert lines == 'foo\n_999\n' c2.alt_labels.append(l1) lines = txt.list_concepts([c1, c2]) lines = ''.join(lines) assert lines == 'foo\n_999\n'
def _prepare_base_data(): """Get base data of all frontend web page""" labels = Label.get_labels() logging.info("labels: {}".format(labels)) # Check user login has_login = (session.get('username', None) is not None) return labels, has_login
def edit(): article_id = request.args.get("id", None) if article_id is None: return redirect(url_for("manage")) article = Article.get_article_by_id(article_id) if not article: return redirect(url_for("manage")) article_id = article.id title = article.title summary = article.summary content = article.content default_label_id = article.labelid labels = Label.get_labels() username = session.get("username", "") return render_template( "backend/post_article.html", id=article_id, title=title, summary=summary, content=content, default_label_id=default_label_id, labels=labels, username=username, )
def from_document(self, doc): """ internalizes values from a dictionary (structure as per as_document) """ from model.label import Label # XXX: coupling! self._id = doc.get('_id') for _type in ('pref', 'alt'): labels = doc.get('labels', {}).get(_type, []) setattr(self, "%s_labels" % _type, [Label('').from_document(label) for label in labels]) return self
def test_show(): c0 = Concept('_666') l1 = Label('foo', 'en') l2 = Label('bar', 'de') lines = txt.show_concept(c0) lines = ''.join(lines) assert lines == '_666\n\nPREFERRED LABELS\n\nALTERNATIVE LABELS\n' c0.pref_labels.append(l1) lines = txt.show_concept(c0) lines = ''.join(lines) assert lines == ('_666\n\n' 'PREFERRED LABELS\n [en] foo\n\n' 'ALTERNATIVE LABELS\n') c0.pref_labels.append(l2) lines = txt.show_concept(c0) lines = ''.join(lines) assert lines == ('_666\n\n' 'PREFERRED LABELS\n [en] foo\n [de] bar\n\n' 'ALTERNATIVE LABELS\n') c0.alt_labels.append(l2) lines = txt.show_concept(c0) lines = ''.join(lines) assert lines == ('_666\n\n' 'PREFERRED LABELS\n [en] foo\n [de] bar\n\n' 'ALTERNATIVE LABELS\n [de] bar\n') c0.alt_labels.append(l1) lines = txt.show_concept(c0) lines = ''.join(lines) assert lines == ('_666\n\nPREFERRED LABELS\n [en] foo\n [de] bar\n\n' 'ALTERNATIVE LABELS\n [de] bar\n [en] foo\n')
def post(): logging.info("** backend post request") if request.method == "POST": logging.info("request form: {}".format(request.form)) ariticle_id = request.form["id"] title = request.form["title"] content = request.form["content"] label_id = int(request.form["label"]) summary = request.form["summary"] status = request.form["status"] if not title: return jsonify({"msg": u"请输入标题", "error": True}) if len(title) > 50: return jsonify({"msg": u"标题太长", "error": True}) if not summary: return jsonify({"msg": u"请输入摘要", "error": True}) if len(summary) > 200: return jsonify({"msg": u"摘要太长", "error": True}) publishtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) kwargs = { "title": title, "summary": summary, "content": content, "labelid": label_id, "publishtime": publishtime, "status": int(status), } if ariticle_id != "": # Update the article id = int(ariticle_id) Article(id=id).update(**kwargs) else: # Insert new article record Article(**kwargs).insert() return jsonify({"redirect": "/backend/manage", "error": False}) username = session.get("username", "") labels = Label.get_labels() default_label_id = 1 return render_template( "/backend/post_article.html", username=username, labels=labels, default_label_id=default_label_id )
def manage(): page = request.args.get("page", 1) logging.info("page: {}".format(page)) try: current_page = int(page) except Exception: return abort(404) uri = str(request.url_rule) template = "/backend/manage_articles.html" # Choose article status article_status = STATUS_PUBLISH if len(uri) > 5 and uri[-5:] == "draft": article_status = STATUS_SAVE template = "/backend/draft.html" logging.info("uri: {}".format(uri)) paging_amount = Article.get_articles_paging_amount() # Deal with current_page params error if current_page > paging_amount or current_page < 1: return abort(404) articles = Article.get_articles_of_current_page(current_page=current_page, article_status=article_status) logging.info("articles: {}".format(articles)) label = Label.get_labels() status = {STATUS_PUBLISH: u"发布", STATUS_SAVE: u"保存"} for article in articles: article.label = label[article.labelid - 1]["name"] article.status = status[article.status] username = session.get("username", "") return render_template( template, username=username, articles=articles, current_page=current_page, paging_amount=paging_amount, uri=uri )
def post_creator(environ, start_response): content_type = environ.get('CONTENT_TYPE', '') if not content_type == 'application/x-www-form-urlencoded': # XXX: TiddlyWeb uses startswith here!? raise HTTP415 # TODO: this might be encapsulated in middleware (cf. tiddlyweb.web.query) content_length = int(environ['CONTENT_LENGTH'] or 0) content = environ['wsgi.input'].read(content_length) data = parse_qs(content, keep_blank_values=True) concept = Concept() # TODO: label language (input/selection currently missing from HTML template) for label_type in ['pref', 'alt']: key = '%s_labels' % label_type for name in data[key]: if name: label = Label(name, lang=None) getattr(concept, key).append(label) _id = STORE.add(concept) response_headers = [('Location', '/concepts/%s' % concept._id)] start_response(HTTP['302'], response_headers) return ['']
def test_get_labels(): labels = Label.get_labels() assert len(labels) == 5
def test_get_label_name(): # {1:Java开发} name = Label.get_label_name(1) assert name == u"Java开发"
def test_setup_label(): my_label = Label("Music") assert (my_label.name == "Music")
def post(self): """ Create a label. **Example Request** .. sourcecode:: json { "labels": [ {"name": "gender"}, {"name": "age"}, ... ] } **Example Response** .. sourcecode:: json { "message": "2 new labels created." } :<header Content-Type: application/json :<header X-Auth: the client's auth token :>json list labels: a list of labels to create :>json str labels[n].name: name of label to create :>header Content-Type: application/json :>json str message: api response message :status 202: created :status 400: invalid request body :status 401: authentication required """ request_json = request.get_json() redis = worker.get_redis() labels = list() # Validate input and create labels for t in request_json['labels']: if t['name'].strip() == '': raise BadRequest('Label name is required') else: try: label = Label(name=t['name'].lower().strip()) g.db.add(label) g.db.flush() redis.publish('label', json.dumps(label.as_dict())) labels.append(label.as_dict()) except IntegrityError: g.db.rollback() raise BadRequest( 'Label "{}" already exists'.format(label.name) ) except AssertionError: g.db.rollback() raise BadRequest( '"{}" contains non-alphanumeric character' .format(t['name']) ) # Save labels g.db.commit() message = '{} new labels created'.format(len(request_json['labels'])) labels = labels response = jsonify( message=message, labels=labels ) response.status_code = 202 return response
def test_create_record_label(app): app.label.create_recording_artist(Label(name="rl_#1", asap="WB86-8RH31.50UTS-J", note="Mens autem qui est in festinabat non facere bonum, voluntas in malo reperit."))
def post(self): ''' Create a label. **Example Request** ..sourcode:: json { "labels": [ {"name": "gender"}, {"name": "age"}, ... ] } **Example Response** ..sourcecode:: json { "message": "2 new labels created." } :<header Content-Type: application/json :<header X-Auth: the client's auth token :>json list labels: a list of labels to create :>json str labels[n].name: name of label to create :>header Content-Type: application/json :>json str message: api response message :status 202: created :status 400: invalid request body :status 401: authentication required ''' request_json = request.get_json() redis = worker.get_redis() labels = list() # Validate input and create labels for t in request_json['labels']: if t['name'].strip() == '': raise BadRequest('Label name is required') else: try: label = Label(name=t['name'].lower().strip()) g.db.add(label) g.db.flush() redis.publish('label', json.dumps(label.as_dict())) labels.append(label.as_dict()) except IntegrityError: g.db.rollback() raise BadRequest( 'Label "{}" already exists'.format(label.name) ) except AssertionError: g.db.rollback() raise BadRequest( '"{}" contains non-alphanumeric character' .format(t['name']) ) # Save labels g.db.commit() message = '{} new labels created'.format(len(request_json['labels'])) labels = labels response = jsonify( message=message, labels=labels ) response.status_code = 202 return response