def add_to_notion(data): token = "d276369250b9a9a9ceb447d36fc46007ed1978ce733e41dca6875c9aa7e67dd16225e9f1bb41aad3b2695b96e24e993462093b1d628ad16ad5db8058eeec27f2b062eae980ffa0e8a02f0778604a" client = NotionClient(token_v2=token) url = "https://www.notion.so/e053742a9c8443dbb03d1f12a38d5a30?v=7c30bcec1be64c3584c6e593fa4ed31e" collection_view = client.get_collection(url) for entry in data: print(entry)
def step_three(): token = os.environ.get('DO_NOT_COMMIT_NOTION_TOKEN') if not token: print( "Can't find token in environment. Did you do step 2 correctly or ran source .config?" ) return client = NotionClient(token_v2=token) parent_page = client.get_block(os.environ.get('NOTION_PAGE_URL')) for block in parent_page.children: try: if block.title == EXPENSE_TABLE_TITLE: print('Expenses Table already exists!') return except: continue cvb = parent_page.children.add_new(CollectionViewBlock) cvb.collection = client.get_collection( client.create_record("collection", parent=cvb, schema=get_collection_schema())) cvb.title = EXPENSE_TABLE_TITLE view = cvb.views.add_new(view_type="table") print('Success! Go back to the README for the last step')
def notion_temp(self): token_v2 = '' #notion 사용자 고유의 토큰 주소 client = NotionClient(token_v2=token_v2) url = '' #자동으로 입력할 noiton 페이지 page = client.get_block(url) # 표 새로 만들고 저장 child = page.children.add_new(CollectionViewBlock) child.collection = client.get_collection( client.create_record( "collection", parent=child, schema={ "title": {"name": "내용", "type": "title"}, "date": {"name": "날짜", "type": "date"} }) ) child.title = '2020년도 회의록' child.views.add_new(view_type="table") row = child.collection.add_row() row.set_property('title', self.title) row.set_property('date', datetime.strptime(self.date, '%Y-%m-%d')) text = row.children.add_new(TextBlock) text.title = self.summary_result return url
class ExpenseTableClient: def __init__(self, token, page_url, table_url): self.client = NotionClient(token_v2=token) self.page = self.client.get_block(page_url) self.table = self.client.get_collection_view(table_url) self.categories = EXPENSE_CATEGORIES def add_expense(self, categories, amt, payment_type, transaction_date, expense='Default Expense', additional=None): row = self.table.collection.add_row() row.Expense = expense row.Categories = categories row.Amount = amt row.Date = transaction_date row.Type = payment_type row.Additional = additional # NOT WORKING def add_month_view(self, page, table_id): collection = self.client.get_collection( table_id) # get an existing collection cvb = page.children.add_new(CollectionViewBlock, collection=collection) view = cvb.views.add_new(view_type="table")
def create_ticket_collection(title, views: [Collection_Type], tickets: [Ticket]): # Get notion config settings notion_config = Notion_config() # Set up client and get page to work on client = NotionClient(token_v2=notion_config.token) page = client.get_block(notion_config.base_page) # Add a new collection collection = page.children.add_new(CollectionViewBlock) collection.collection = client.get_collection( client.create_record("collection", parent=collection, schema=ticket_collection_scheme(tickets))) now = datetime.now() dt_string = now.strftime("%d/%m/%Y %H:%M:%S") collection.title = title + ' ' + dt_string # Add desired Views for view in views: collection.views.add_new(view_type=view.value) return collection
class NotionInterface: def __init__(self): self.token_v2 = TOKEN_V2 self.client = NotionClient(token_v2=self.token_v2) self.strava_page_title = "Strava" self.strava_table_title = "Activity Logbook" def get_strava_page(self): strava_page = None for page in self.client.get_top_level_pages(): if self.strava_page_title == page.title: strava_page = page if strava_page is None: raise LookupError( f"Unable to find Strava page, is there a page with a " f"title of '{self.strava_page_title}' in your workspace?" ) return strava_page def create_activity_log_table(self): strava_page = self.get_strava_page() # Check if we've a table already for block in strava_page.children: if hasattr(block, 'title') and block.title == self.strava_table_title: return block # Create a table strava_table = strava_page.children.add_new(CollectionViewBlock) strava_table.collection = self.client.get_collection( self.client.create_record("collection", parent=strava_table, schema=SCHEMA) ) strava_table.title = self.strava_table_title strava_table.views.add_new(view_type="table") return strava_table def add_row_to_table(self, table, data): # HACK - needs to happen to work! table.collection.parent.views rows = table.collection.get_rows() if not any([r.name == data.name and r.date.start.date() == data.start_date_local.date() for r in rows]): row = table.collection.add_row() row.set_property("title", data.name) row.set_property("date", data.start_date_local) row.set_property("type", data.type) row.set_property("distance (m)", data.distance) row.set_property("time (s)", data.moving_time) row.set_property("cals", data.kilojoules) print(f'Added {data.name} on {data.start_date_local} to Notion!') else: print(f'Skipping {data.name} for {data.start_date_local}')
def main(): # login client = NotionClient(token_v2=TOKEN) # create new page page = client.get_block(PAGE_URL) if len(page.children) > 1: # if table exists del page.children[1] child = page.children.add_new(CollectionViewBlock) child.collection = client.get_collection( client.create_record( "collection", parent=child, schema=get_schema_todo()) ) child.title = 'Ecampus Assignments' child.views.add_new(view_type="table") for assignment in ASSIGNMENT: row = child.collection.add_row() row.set_property('title', assignment['assignment_title']) row.set_property('course', assignment['course']) row.set_property('date', assignment['assignment_date']) row.set_property('submit', assignment['is_submitted']) else: # if table not exists child = page.children.add_new(CollectionViewBlock) child.collection = client.get_collection( client.create_record( "collection", parent=child, schema=get_schema_todo()) ) child.title = 'Ecampus Assignments' child.views.add_new(view_type="table") for assignment in ASSIGNMENT: row = child.collection.add_row() row.set_property('title', assignment['assignment_title']) row.set_property('course', assignment['course']) row.set_property('date', assignment['assignment_date']) row.set_property('submit', assignment['is_submitted'])
def add_notion(token_v2, url, df): # update comments try: df = update_comments_table(token_v2, url, df) print('[NOTION] Update comments table') except: print('[NOTION] Create new comments table') # add check box property df['check'] = False df = df.sort_values(['check', 'date'], ascending=[False, False]) print(df.info()) client = NotionClient(token_v2=token_v2) page = client.get_block(url) # clean page if len(page.children) > 0: for i in range(len(page.children)): del page.children[i] child = page.children.add_new(CollectionViewBlock) child.collection = client.get_collection( client.create_record("collection", parent=child, schema=get_schema_comments(df.columns))) # set korea time kor_time = datetime.datetime.utcnow() + datetime.timedelta(hours=9) child.title = kor_time child.views.add_new(view_type='table') for i in range(len(df)): row = child.collection.add_row() row.set_property('title', str(i)) for col in df.iloc[i].index: if col == 'check': row.set_property(col, bool(df.iloc[i][col])) else: row.set_property(col, str(df.iloc[i][col]))
def get_collection(): token = request.args.get("token") client = NotionClient(token) url = request.args.get('url') obj = {"properties": [], "data": []} cv = client.get_collection_view(url) cProperties = cv.collection.get_schema_properties() for prop in cProperties: if (prop['type'] == 'relation'): print("here") options = [] relation = {"slug": prop["slug"], "options": []} ## list all options collection = client.get_collection(prop['collection_id']) project_rows = collection.get_rows() print(project_rows) for project_row in project_rows: title = project_row.get_property("title") id = project_row.id options.append({"title": title, "id": id}) prop["options"] = options obj['properties'] = cProperties cRows = cv.collection.get_rows() data = [] for row in cRows: thisRow = {} for prop in cProperties: thisRow[prop['slug']] = get_property_value_in_row(row, prop) data.append(thisRow) obj['data'] = data response = app.response_class(response=json.dumps(obj), status=200, mimetype='application/json') return response
class Upload: def __init__(self, config): if "notion" in config: if "token" not in config["notion"]: print("token for notion is not present!") exit() if "page" not in config["notion"]: print("page for notion is not present!") exit() else: print("notion is missing in config.json") exit() if "backtest_results" not in config: print("backtest_results path is missing in config.json") exit() self.config = config self.client = NotionClient(token_v2=config["notion"]["token"]) self.cv = self.client.get_collection_view(config["notion"]["page"]) present_strategies = self.get_collection_strategies() present_results = self.get_backtest_results(config["backtest_results"]) self.compare_and_add_new(present_strategies, present_results) def compare_and_add_new(self, present_strategies, results): for result in results: report, trades = self.calculate_report(result["trades"]) present = False for strategy in present_strategies: if result["strategy"] in strategy: present = True if not present: row = self.cv.collection.add_row() row.avg_profit_perc = round(report["avg_profit_%"], 7) row.buys = report["buys"] row.loses = report["loss"] row.strategy = result["strategy"] row.title = result["strategy"] row.title_plaintext = result["strategy"] row.cum_profit_perc = round(report["cum_profit_%"], 6) row.total_profit_mc = round(report["total_profit"], 6) row.wins = report["wins"] row.rating = ["To Do"] self.create_detail_page(result["strategy"], row.id, report["pairs"]) def create_detail_page(self, strategy, id, pairs_info): eid = id.replace("-", "") page = self.client.get_block("https://www.notion.so/" + strategy + "-" + eid) header1 = page.children.add_new(HeaderBlock) header1.title = "Strategy Information" header2 = page.children.add_new(HeaderBlock) header2.title = "Review" cv = self.client.get_collection_view(self.config["notion"]["sample"]) collection = self.client.get_collection( cv.collection.id) # get an existing collection cvb = page.children.add_new(CollectionViewBlock, collection=collection) view = cvb.views.add_new(view_type="table") for pair in pairs_info: try: row = cvb.collection.add_row() row.pair = pair["pair"] row.buys = pair["buys"] row.wins = pair["wins"] row.loss = pair["loss"] row.avg_profit_perc = pair["avg_profit_%"] row.cum_profit_perc = pair["cum_profit_%"] row.tot_profit_mc = pair["profit"] row.avg_duration = pair["avg_duration"] except Exception as e: print(e) def calculate_report(self, trades): report = {} report["buys"] = len(trades) trade_info = [] for trade in trades: t_info = {} t_info["pair"] = trade[0] t_info["percentage"] = trade[1] t_info["buy_date"] = trade[2] t_info["sell_date"] = trade[3] t_info["unknown1"] = trade[4] t_info["duration"] = trade[5] t_info["buy_price"] = trade[6] t_info["sell_price"] = trade[7] t_info["unknown2"] = trade[8] t_info["reason"] = trade[9] trade_info.append(t_info) report["pairs"] = [] report["wins"] = 0 report["loss"] = 0 report["total_profit"] = 0 report["cum_profit_%"] = 0 report["duration"] = 0 for trade in trade_info: present = False for i, rep in enumerate(report["pairs"]): if trade["pair"] in rep["pair"]: report["pairs"][i]["buys"] += 1 report["pairs"][i]["cum_profit_%"] += trade["percentage"] report["pairs"][i]["duration"] += trade["duration"] report["pairs"][i]["profit"] += trade["percentage"] * 0.001 if t_info["percentage"] >= 0: report["pairs"][i]["wins"] += 1 else: report["pairs"][i]["loss"] += 1 present = True if not present: info = {} info["pair"] = trade["pair"] info["buys"] = 1 info["cum_profit_%"] = trade["percentage"] info["duration"] = trade["duration"] info["profit"] = trade["percentage"] * 0.001 if trade["percentage"] >= 0: info["loss"] = 0 info["wins"] = 1 else: info["loss"] = 1 info["wins"] = 0 report["pairs"].append(info) for rep in report["pairs"]: report["wins"] += rep["wins"] report["loss"] += rep["loss"] report["total_profit"] += rep["profit"] report["cum_profit_%"] += rep["cum_profit_%"] report["duration"] += rep["duration"] rep["avg_profit_%"] = rep["cum_profit_%"] / rep["buys"] rep["avg_duration"] = rep["duration"] / rep["buys"] report["avg_profit"] = report["total_profit"] / report["buys"] report["avg_profit_%"] = report["cum_profit_%"] / report["buys"] return report, trade_info def get_collection_strategies(self): strategies = [] for row in self.cv.collection.get_rows(): strategies.append(row.strategy) return strategies def get_backtest_results(self, path): results = [] for root, dirs, files in os.walk(path): for file in files: information = {} filenamelist = file.split("-") strategy = filenamelist[2] strategy = strategy.replace(".json", "") information["strategy"] = strategy try: with open(os.path.join(root, file)) as f: information["trades"] = json.load(f) except Exception as e: print(e) results.append(information) return results
# get_posts_from_database.py import os import datetime import config from notion.client import NotionClient from textwrap import indent client = NotionClient(config.NOTION_TOKEN) contents_collection = client.get_collection(config.COLLECTION_ID) posts = contents_collection.get_rows() def parse_blocks(blocks): text = '' for block in blocks.children: # Handles H1 if (block.type == 'header'): text = text + '# ' + block.title + '\n\n' # Handles H2 if (block.type == 'sub_header'): text = text + '## ' + block.title + '\n\n' # Handles H3 if (block.type == 'sub_sub_header'): text = text + '### ' + block.title + '\n\n' # Handles Code Blocks if (block.type == 'code'): text = text + '```' + block.language.lower( ) + '\n' + block.title + '\n```\n\n' # Handles Callout Blocks if (block.type == 'callout'):
import pandas as pd # Obtain the `token_v2` value by inspecting your browser cookies on a logged-in session on Notion.so token = "8c367e647c7f3db99590cf5c6a12eaf148c13c825c88134327355f1f1838f54c7d7e5e9636a7b65bf6b91b09fc1e6958fde77bed6a0bb2cb721eb61e0c5984fe4d82e92fa48ef4ae0a706976755e" #variável client é o "cliente" aberto no login do navegador. qual a segurança disso? posso tentar testar client = NotionClient(token_v2=token) #O DONSA DONSA = client.get_block("29af322f-3eb3-40a7-89be-2dd7afd78408") #Todas as páginas do DONSA HOMEPAGE = client.get_block("29cd1701-b3f6-495e-b94e-535a2c03be37") #sandbox pro python sandbox = client.get_block("ab9ebc44-60fb-4dd6-8bb0-f4ca08d9730e") Calendário = client.get_block("125a4883-97b2-4181-a46c-e0e42f40cd91") coluna = client.get_collection("058cd2b2-735c-45a6-bc75-6be2b59caaa1") filter_params = [{"TIPO": "DataCamp"}] #print(client.get_block("125a4883-97b2-4181-a46c-e0e42f40cd91")) #print(sandbox.children[1]) #sandbox.children.add_new(PageBlock, title='foi meu copaero') #sandbox.children[0].add_new(PageBlock, title='foi meu copaero') #for child in HOMEPAGE.children: # print(child) #input("ENTER EXIT")
import os from notion.client import NotionClient # Init NotionClient NOTION_TOKEN = os.getenv("NOTION_TOKEN") HOME_URL = os.getenv("DOCUMENTS_URL") # client = NotionClient(token_v2=NOTION_TOKEN, monitor=True, start_monitoring=True) client = NotionClient(token_v2=NOTION_TOKEN) blog_home = client.get_block(HOME_URL) COLLECTION_ID = blog_home.collection.id collection = client.get_collection(COLLECTION_ID) posts = collection.get_rows() # post status str publish_ready = "🚀Ready to Publish" published = "📰Published" # timezone for displaying on log timezone_log = "Asia/Seoul" # the absolute path where you want to place markdown file post_path = "/home/ubuntu/blog/" # the absolute path of repository where_am_i = "/home/ubuntu/jaekwang/notion-markdown-updater/" # auto push when change made auto_deploy = False
'type': 'multi_select', "options": [{ "id": "dd3500bb-eb53-4c74-9c4b-2f84d508acde", "value": "Day One" }] } } for source_file in args.files: journal_name = Path(source_file).stem print(f'Importing journal: {journal_name}') journal_page = archive_page.children.add_new(CollectionViewPageBlock) journal = client.get_collection( client.create_record('collection', parent=journal_page, schema=journal_schema)) journal_page.collection = journal journal_page.views.add_new(view_type='table') journal_page.title = journal_name with open(source_file) as fp: source_data = json.load(fp) for entry in source_data['entries']: if 'text' not in entry: continue text = entry['text'].splitlines(keepends=False) title = text[0] body = "\n".join(text[1:])
client = NotionClient(token_v2=token_v2) # Access a database using the URL of the database page or the inline block page = client.get_block(page_link) page.title = "Kindle Highlights" page.set( "format.page_cover", "https://www.incimages.com/uploaded_files/image/1920x1080/getty_598063032_349381.jpg" ) page.icon = "https://i.pinimg.com/originals/2c/fc/93/2cfc93d7665f5d7728782700e50596e3.png" cvb = page.children.add_new(CollectionViewBlock) cvb.collection = client.get_collection( client.create_record("collection", parent=cvb, schema=get_collection_schema())) cvb.title = "Read them!" view = cvb.views.add_new(view_type="table") gallery_view = cvb.views.add_new(view_type="gallery") for book in data.keys(): print(book) #col=collection. row = cvb.collection.add_row() row.name = book book_description, image_link, book_author, page_count, average_rating, book_categories = search( book) if image_link.startswith("'") and image_link.endswith("'"): image_link = image_link[1:-1] if image_link.startswith('"') and image_link.endswith('"'):
} client = NotionClient(token_v2='6fbfb3606dbe98bc33276b43adc67c82b3f98a4cfe6ce13fb1d9695ea7dbb6be8655609124f2a1b6e9dbcf21f983e20066e68392a3832905d8a7d3486796085f80859d8baa7c0b8f478e30bd9d6c') page = client.get_block("https://www.notion.so/Test-task-figured-out-4a3c87d8f25f429b9b350567d4705191") today = datetime.date.today() for child in page.children: block_type = child.get("type") if block_type == 'collection_view': collection_id = child.collection.id #get the lines we need to work with items = client.get_collection(collection_id) collection_rows = items.get_rows() #create a DONE_list to work with list_of_tasks = [] for row in collection_rows: if row.get_all_properties()['status'] == 'DONE': list_of_tasks.append(row) #checking the status of tasks in 'DONE': for task in list_of_tasks: flag = False set_date = task.get_all_properties()['set_date'].start due_date = task.get_all_properties()['due_date'].start if set_date > today: