def signin(db): session = bottle.request.environ.get('beaker.session') username = bottle.request.forms.username.strip().lower() email = bottle.request.forms.email.strip().lower() username_re = re.compile(r'^[_0-9A-Za-z]{5,20}$') email_re = re.compile(r'^[a-zA-Z0-9._%-+]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$') password = bottle.request.forms.password if not username_re.match(username): return {'ok':False,'msg':u"Имя пользователя должно быть не менее 5 и \ не более 20 символов, и содержать латинские буквы и цифры и знак подчеркивания"} if not email_re.match(email): return {'ok':False, 'msg': u"Неправильный формат e-mail"} if len(password) < 6: return {'ok':False,'msg':u"Пароль должен содержать не менее 7 символов"} user = db.query(User).filter(or_(User.name==username,User.email==email)).first() if not user: new_user = User(name = username, password=hashlib.sha256(password).hexdigest(), email = email) new_user_notebook = Notebook(name=u"Блокнот", deflt=True) new_user_notebook.user = new_user new_note = Note(text=u"Добро пожаловать в Notebook!", title=u"Первая заметка"); new_user_notebook.notes.append(new_note); db.add(new_user) db.commit() session['user_id'] = new_user.id return {'ok':True, 'msg':u"Пользователь {0} создан.".format(new_user.name)} else: return {'ok':False,'msg':u"Пользователь с таким именем или адресом e-mail уже существует"}
def newNotebook(notebook): existing_notebook = Notebook.query.filter( Notebook.name == notebook.get("name")).one_or_none() if existing_notebook is None: newNotebook = Notebook(id=notebook.get("id"), name=notebook.get("name"), status="pending") db.session.add(newNotebook) db.session.commit() request_rpc = RpcClient() print(" [x] Requesting creating notebook") message = { 'id': newNotebook.id, 'name': newNotebook.name, 'type': 'Notebook', 'action': 'Create', } response = request_rpc.call(message) print(" [.] Successfully") return jsonify(newNotebook.serialize()), 201 else: abort(409, "Notebook name exists already")
def create_notebook(db): session = bottle.request.environ.get('beaker.session') user_id = session.get('user_id',0) try: data = bottle.request.json try: new_notebook = Notebook(user_id = user_id, name=data['name'] ) except KeyError: return {} db.add(new_notebook) db.commit() return json.dumps(new_notebook.to_dict(), ensure_ascii=False) except NoResultFound: return {}
def create(user, name, color): """ Create a new notebook """ if len(name) > 24: raise UnprocessableEntity(description="NOTEBOOK_NAME_MAX_LENGTH") current_time = int(time.time()) notebook = Notebook(name=name, color=color, user=user.id, created_at=current_time, updated_at=current_time) notebook.save() return notebook.transform()
def create_notebook(self, parent_id): with NotebookFormDialog(self) as dlg: if dlg.ShowModal() == wx.ID_OK: notebook = Notebook.create(name=dlg.get_name(), description=dlg.get_description(), parent_id=parent_id) self.nav_panel.note_tree.append_notebook(notebook)
def _load_notebooks(self, parent_node, parent_id): child_notebooks = Notebook.select().where( Notebook.parent_id == parent_id) for notebook in child_notebooks: item = self.AppendItem(parent_node, notebook.name, data=notebook) self._load_notebooks(item, notebook.id) self.ExpandAll()
def move_notebook(self, notebook_id): with NotebookChoiceDialog(self) as dlg: if dlg.ShowModal() == wx.ID_OK: notebook = Notebook.find(notebook_id) source_id, target_id = notebook.move( dlg.get_selected_notebook_id()) if source_id != target_id: self.nav_panel.note_tree.move_notebook_to( target_id, notebook)
def _build_note_tree(self, parent_id, parent_item): child_notebooks = Notebook.select().where( Notebook.parent_id == parent_id) for note_book in child_notebooks: item = self.AppendItem(parent_item, '', data=self.get_notebook_info(note_book)) self.set_item_text(item) self.tree_node_dict[note_book.id] = item self._build_note_tree(note_book.id, item)
def _create_notebook(self, _): with NotebookDialog(self) as dialog: if dialog.ShowModal() == wx.ID_OK: notebook = Notebook.create( name=dialog.get_name(), description=dialog.get_description(), parent_id=self.GetSelection().GetData().id) item = self.AppendItem(self.GetSelection(), notebook.name, data=notebook) self.DoSelectItem(item)
def delete_notebook(self, notebook_id): notebook = Notebook.find(notebook_id) caption = _("notebook.delete_dialog_title", v1=notebook.name) message = _("notebook.delete_dialog_message") with GenericMessageDialog(message, caption) as dlg: if dlg.ShowModal() == wx.ID_OK: self.nav_panel.note_tree.delete_selected_notebook() self.list_panel.empty() self.detail_panel.remove_note() self.todo_panel.empty() notebook.delete_instance()
def edit_notebook(self, notebook_id): notebook = Notebook.find(notebook_id) old_name = notebook.name with NotebookFormDialog(self, notebook) as dlg: if dlg.ShowModal() == wx.ID_OK: notebook.update_instance(name=dlg.get_name(), description=dlg.get_description()) self.list_panel.update_header_title(dlg.get_name()) if old_name != notebook.name: self.nav_panel.note_tree.update_selected_notebook( notebook.name)
def get(self, notebook_id): template_vals = {'name_of_user': users.get_current_user().nickname()} notebook = Notebook.get_by_id(int(notebook_id)) # Get all documents for notebook titles = list() docs = list() for doc in notebook.document_ids: docs.append(int(doc)) titles.append(Document.get_by_id(int(doc)).title) template_vals['titles'] = titles template_vals['nb_id'] = int(notebook_id) template_vals['doc_ids'] = docs render(self, template_vals, 'notebook-documents.html')
def get_notebooks(self, user_id): sleep(0.10) notebooks = {} try: # notebook_ids = user.notebook_ids notebooks = list() # for notebook_id in notebook_ids: notebook_iter = Notebook.query(Notebook.user_id == user_id).order(Notebook.title).iter() for notebook in notebook_iter: notebooks.append(notebook) except BaseException: pass return notebooks
def __init__(self, parent): super().__init__(parent, agwStyle=customtreectrl.TR_HAS_BUTTONS | customtreectrl.TR_FULL_ROW_HIGHLIGHT | customtreectrl.TR_ELLIPSIZE_LONG_ITEMS | customtreectrl.TR_TOOLTIP_ON_LONG_ITEMS) self.root = self.AddRoot("所有笔记", data=Notebook()) self._load_notebooks(self.root, None) self._init_ui() self._init_popup_menu() self._init_event() wx.CallAfter(self.DoSelectItem, self.GetRootItem().GetChildren()[0])
def __init__(self, parent): super().__init__(parent, title=_("notebook_choice_dialog.title")) self.tree_ctrl = customtreectrl.CustomTreeCtrl( self, style=wx.TR_FULL_ROW_HIGHLIGHT, size=(400, 200)) panel_font = self.GetFont() panel_font.SetPointSize(panel_font.GetPointSize() + 1) self.tree_ctrl.SetFont(panel_font) self.tree_ctrl.root = self.tree_ctrl.AddRoot( _("notebook_choice_dialog.root_node")) self.tree_ctrl.SetItemData(self.tree_ctrl.root, None) total_note_books = Notebook.all() root_note_books = list( filter(lambda n: n.parent_id == None, total_note_books)) child_note_books = list( filter(lambda n: n.parent_id != None, total_note_books)) for note_book in root_note_books: item = self.tree_ctrl.AppendItem(self.tree_ctrl.root, note_book.name, data=note_book.id) self._build_note_tree(note_book.id, item, child_note_books) self.tree_ctrl.ExpandAll() self.tree_ctrl.SetSpacing(20) main_sizer = wx.BoxSizer(wx.VERTICAL) main_sizer.Add(self.tree_ctrl, flag=wx.EXPAND | wx.TOP, border=20) btn_sizer = wx.StdDialogButtonSizer() btn_sizer.AddButton(wx.Button(self, wx.ID_CANCEL, _("dialog_cancel"))) btn_ok = wx.Button(self, wx.ID_OK, _("dialog_ok")) btn_ok.SetDefault() btn_sizer.AddButton(btn_ok) btn_sizer.Realize() main_sizer.Add(btn_sizer, flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, border=5) main_sizer.Fit(self) self.SetSizer(main_sizer) self.CenterOnScreen() self.Bind(wx.EVT_BUTTON, self.on_save, id=wx.ID_OK)
import config from models import Notebook, Training, Endpoint from datetime import datetime NOTEBOOKS = [] TRAININGS = [] ENDPOINTS = [] config.createDB() db.create_all() for notebook in NOTEBOOKS: n = Notebook(id=notebook.get("id"), name=notebook.get("name")) db.session.add(n) for training in TRAININGS: t = Training(id=training.get("training_id"), name=training.get("name")) for endpoint in training.get("endpoints"): endpoint_id, endpoint_name, createdDate = endpoint n.endpoints.append( Ednpoint(id=endpoint_id, name=endpoint_name, created_date=datetime.strptime(created_date, "%Y-%m-%d %H:%M:%S"))) db.session.add(t) for endpoint in ENDPOINTS: e = Endpoint(id=endpoint.get("id"), name=endpoint.get("name"))
def list_note(self, notebook_id): notebook = Notebook.find(notebook_id) query = notebook.notes.order_by(Note.updated_at.desc()) notes = [n for n in query] self.list_panel.add_notes(notes, notebook) self._display_note_list(notes)
from models import Notebook, TextNote, VideoNote bio = Notebook("Bio 201 Notes") bio.notes.append(TextNote("This is the first day of Bio 201")) bio.notes.append(TextNote("Final exam is 95%.")) bio.notes.append(VideoNote("https://www.youtube.com/watch?v=PKffm2uI4dk")) bio.display() bio.save("bio201.txt") bio.load("bio201.txt") print(bio.to_json())
import os from config import db from models import Notebook, Training, Endpoint NOTEBOOKS = [{"notebook_name": "FirstNotebook", "notebook_id": "12345"}] TRAININGS = [{"training_name": "FirstTraining", "training_id": "12345"}] ENDPOINTS = [{"endpoint_name": "FirstEndpoint", "endpoint_id": "12345"}] if os.path.exists("mimir.db"): os.remove("mimir.db") db.create_all() for notebook in NOTEBOOKS: n = Notebook(notebook_id=notebook.get("notebook_id"), notebook_name=notebook.get("notebook_name")) db.session.add(n) for training in TRAININGS: t = Training(training_id=training.get("training_id"), training_name=training.get("training_name")) db.session.add(t) for endpoint in ENDPOINTS: e = Endpoint(endpoint_id=endpoint.get("endpoint_id"), endpoint_name=endpoint.get("endpoint_name")) db.session.add(e) db.session.commit()
from models import User, Notebook, Note, Base import random, codecs try: os.unlink('database.sqlite') except OSError: pass Base.metadata.create_all(db.engine) def pwd_hash(t): return hashlib.sha256(t).hexdigest() Session = sessionmaker(bind=db.engine) session = Session() admin_user = User(name="admin", admin=True, password=hashlib.sha256("admin").hexdigest(), email="*****@*****.**" ) ntb = Notebook( name=u"Блокнот", deflt=True, published=False) ntb.notes = [ Note(title=u'Заголовок заметки', text=u"Добро пожаловать, admin") ] ntb.user = admin_user session.add(admin_user) session.commit() #fill database f = open('/usr/share/dict/words') allwords = [] users = [] for a in f: if 7 < len(a) < 10: allwords.append(a.strip().lower())
def notebook_action_menu_callback(self, menu): if Notebook.count() == 1: menu.Enable(self.menu_delete_notebook_id, False)