--- lang:ja-jp ###### tags: `open` --- # pyhackmd hackmd API endpointを利用。 (hackmd-cli, codimd, @hackmd/apiから参照) https://github.com/codimd/cli https://github.com/hackmdio/hackmd-cli node-modules/@hackmd/api ## 環境変数 ||| |-|-| |HMD_CLI_SERVER_URL|省略した場合`https://hackmd.io`が代入される| |HMD_CLI_ID|login用のemail| |HMD_CLI_PASSWORD|login用のpassword| ## How To Use ```python s = HackMDSession() s.login() s.get_history() # -> s.history content="# new page\n## section\n" s.create(content=content, tags=["tag1", "tag2"]) ``` ## source ```python from requests import Session import os import re class HackMDSession(Session): """HackMDSession""" def __init__(self, server_url=""): self.server_url = server_url or \ os.environ.get("HMD_CLI_SERVER_URL") or \ "https://hackmd.io" Session.__init__(self) def login(self, email="", password=""): """Login with environ variable""" email_in = email or os.environ.get("HMD_CLI_ID") password_in = password or os.environ.get("HMD_CLI_PASSWORD") if email_in == "" or password_in == "": print("email or password is wrong") return login_info = {"email": email_in, "password": password_in} orig_headers = { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'} res_tmp = self.get(self.server_url) csrf = re.findall(r'(?<=csrf-token. content=").+(?=")', res_tmp.content.decode("utf-8"))[0] data = self.remake_data(login_info) res = self.post(f"{self.server_url}/login", data=data, headers=self.remake_headers(orig_headers)) if not self.isLogin(): print("Login Failed") return print("Login Successed") def remake_data(self, orig_data={}): return "&".join([f"{k}={v}" for k, v in orig_data.items()]).encode('utf-8') def remake_headers(self, orig_headers={}): res_tmp = self.get(self.server_url) try: csrf = re.findall(r'(?<=csrf-token. content=").+(?=")', res_tmp.content.decode("utf-8"))[0] except: print("There is no csrf token") csrf = "" orig_headers.update( {'User-Agent': f"Python Jupyter", 'X-XSRF-Token': csrf.encode("utf-8")}) return orig_headers def isLogin(self): """check Logined or not""" res_tmp = self.get(f"{self.server_url}/me") if res_tmp.json()["status"] == "ok": return True else: return False def create(self, orig_content="", tags=[]): """create new note""" if not self.isLogin(): print("Not Logined") return content = f"---\nlang:ja-jp\n###### tags: {' '.join([f'`{s}`' for s in tags])}\n---\n{orig_content}" orig_data = {"content": content} orig_headers = { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'} res = self.post(f"{self.server_url}/new", data=self.remake_data( orig_data), headers=self.remake_headers(orig_headers)) return res def get_history(self): """return list of id, title, date and tags""" if not self.isLogin(): print("Not Logined") return res = self.get(f"{self.server_url}/history") try: self.history = res.json()["history"] return res.json()["history"] except Exception as e: print(f"Error Occured : {e}") return res def download(self, note_id, dl_format="md"): """download with note_id""" if not self.isLogin(): print("Not Logined") return if dl_format == "pdf": # if in hackmd.io, not pdf res = self.get(f"{self.server_url}/{note_id}/pdf") elif dl_format == "slide": res = self.get(f"{self.server_url}/{note_id}/slide") elif dl_format == "md": res = self.get(f"{self.server_url}/{note_id}/download") return res.content ```