fastapi学习笔记
status
Published
date
Mar 16, 2021
slug
fastapi
summary
fastapi学习笔记
category
学习思考
tags
Fast API
简单运行
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
def index():
		return {'hello':'world'}
一个简单的项目

main.py

from fastapi import FastAPI  
import uvicorn
import msg,ip

app = FastAPI()
app.include_router(msg.router, prefix="/msg")
app.include_router(ip.router, prefix="/ip")

@app.get('/')
async def index():
    return '首页'


if __name__ == '__main__':
    uvicorn.run(app='main:app',host='0.0.0.0',port=12345,reload=True,debug=True)

ip.py

from fastapi import APIRouter
import requests
from bs4 import BeautifulSoup
import json
from random import choice
router = APIRouter()
def api():
    url = 'http://proxylist.fatezero.org/proxy.list'
    headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}
    res = requests.get(url,headers=headers)
    res.encoding = "utf-8"
    s = res.text
    data = []
    for i in s.split('\n'):
        try:
            ip = str(json.loads(i)['host'])+':'+str(json.loads(i)['port'])
            msg = {"ip":ip,"country":str(json.loads(i)['country']),"type":str(json.loads(i)['type']),"response_time":str(json.loads(i)['response_time']),'weixin':'zhaoipxyz'}
            data.append(msg)
        except:
            pass
    return data

def choiceone():
    ip = choice(api())
    return ip

@router.get('/')
async def msg():
    return choiceone()

msg.py

from peewee import *
import requests,time
from bs4 import BeautifulSoup

db = PostgresqlDatabase('kfnmhpuuszajss:4bb62ccc1b91797c653df18b169ad38f541489c9ed56d0770ae67823b5663227@ec2-54-156-149-189.compute-1.amazonaws.com:5432/d14bupst16squ7')

class BaseModel(Model):
    class Meta:
        database = db

class Share(BaseModel):
    title = CharField(verbose_name='标题', null=False, index=True)
    link = CharField(verbose_name='链接', null=False)
    site = CharField(verbose_name='来源站点', null=False)
    pubtime = DateTimeField(verbose_name='发布时间', null=False, default=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    class Meta:
        table_name = 'share'
try:
    Share.create_table()
except:
    print('表已存在')

class Xianbao:
    def __init__(self):
        self.headers = {
            'User-Agent': 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36'
            }

    def wgzj(self):
        site = '网购之家'
        r = requests.get('http://www.wgzj.cn/bbs/forum-2-1.html',headers=self.headers)
        html = r.text
        bs = BeautifulSoup(html,'html.parser')
        links= bs.findAll('a',class_='s xst')
        for link in links:
            title= link.text
            url = 'http://www.wgzj.cn/bbs/' + link['href']
            if Share.get(link==url).frist():
                print(title,'数据已存在!')
            else:
                Share.create(title=title,site=site,link=link)
                print(title,'采集成功!')
            

    def kxd(self):
        site ='科学刀'
        r =requests.get('https://kxdao.net/forum-42-1.html',headers=self.headers)
        html = r.text
        bs = BeautifulSoup(html,'html.parser')
        links = bs.findAll('a',class_='s xst')
        for link in links:
            title = link.text
            url = link['href']
            if Share.get(link==url).frist():
                print(title,'数据已存在!')
            else:
                Share.create(title=title,site=site,link=link)
                print(title,'采集成功!')

    def leyu(self):
        site = '乐愚社区'
        r = requests.get('https://bbs.leyuz.net/f/xianbao', headers=self.headers)
        html = r.text
        bs = BeautifulSoup(html,'html.parser')
        links = bs.findAll('a',class_="tag-title")
        for link in links:
            title = link.text
            url = 'https://bbs.leyuz.net' + link['href']
            if Share.get(link==url).frist():
                print(title,'数据已存在!')
            else:
                Share.create(title=title,site=site,link=link)
                print(title,'采集成功!')

    def xb0818(self):
        site = '线报0818'
        r = requests.get('http://www.0818tuan.com/list-1-0.html', headers=self.headers)
        html = r.text
        bs = BeautifulSoup(html, 'html.parser')
        links = bs.findAll('a', href=re.compile(r"/xbhd/\d+\.html"))
        for link in links:
            title = link.text
            url = "http://www.0818tuan.com" + link['href']
            if Share.get(link==url).frist():
                print(title,'数据已存在!')
            else:
                Share.create(title=title,site=site,link=link)
                print(title,'采集成功!')
IP检测
 
Article Details
如何部署MongoDB并开启远程访问Docker版
status
Published
date
Mar 15, 2021
slug
mongodb
summary
Docker部署MongoDB
category
技术分享
tags
Docker
 
  • Docker安装
    • 安装方法pull最新版本mongo运行 -name设置名称 v挂载数据 p端口映射 d后台运行设置用户进入mongodb容器进行设置进入 admin 的数据库创建管理员用户创建有可读写权限的用户. 对于一个特定的数据库, 比如'demo'
      • docker pull mongo
        mkdir ~/mongo #随便啦自己看着想放哪里都好
        docker run --name mongodb -v ~/mongo:/data/db -p 27017:27017 -d mongo
        docker exec -it mongodb bash
        mongo
        use admin
        db.createUser({user: "admin",pwd: "pwd",roles: [ { role: "userAdminAnyDatabase", db: "admin"}]})
        db.createUser({user: 'username',pwd: 'pwd',roles: [{role: "readWrite", db: "demo"}]})
      • 远程访问
        • 在 mongodb 的容器当中操作修改bindIP
Article Details
近期的影视剧
status
Published
date
Mar 6, 2021
slug
log1
summary
category
学习思考
tags
影视
之前一直觉得韩剧听无趣的,大多都是无脑的偶像剧,但最近看了一些韩剧貌似很不错的呢,比如最近看的《窥探》《隧道》《西西弗斯的神话》。
国产剧从若干年的《水浒传》之后基本就没怎么看过,每次有些什么新剧热剧,看不到几分钟就觉得无趣或者脑残,国内的演员演技基本为负数,编剧基本都脑瘫,完全看不下去。
今年春节,电影就看了个《哪吒重生》,国产动画最近几年进步还是挺大的,哪吒系列,魁拔系列都不错。
电报上看到有人分享《你好,李焕英》,看了大概半小时吧,很无趣的小品。
 
Article Details
自动阅读赚钱项目的autojs脚本分享
status
Published
date
Mar 5, 2021
slug
autojs
summary
category
技术分享
tags
快速极速版
抖音极速版
趣头条
中青看点
看看赚
七猫免费小说
抖音评论
抖呱呱极速版
趣头条
刷宝
微信红包
Article Details
影视网站导航
status
Published
date
Mar 5, 2021
slug
movie
summary
category
资源分享
tags
一些平常看剧的网站,主要是美剧,港剧,最近发现韩剧也不错呢。
 
Article Details
notion使用Workers绑定域名
status
Published
date
Mar 5, 2021
slug
notionworkers
summary
category
技术分享
tags

演示效果

代码
/* CONFIGURATION STARTS HERE */

  /* Step 1: enter your domain name like notion.afuture.me */
  const MY_DOMAIN = '你的域名';
  
  /*
   * Step 2: enter your URL slug to page ID mapping
   * The key on the left is the slug (without the slash)
   * The value on the right is the Notion page ID
   */
  const SLUG_TO_PAGE = {
    '': 'pageid',
  };
  
  /* Step 3: enter your page title and description for SEO purposes */
  const PAGE_TITLE = '';
  const PAGE_DESCRIPTION = '';
  
  /* Step 4: enter a Google Font name, you can choose from https://fonts.font.im */
  const GOOGLE_FONT = '';
  
  /* Step 5: enter any custom scripts you'd like */
  const CUSTOM_SCRIPT = ``;
  
  /* CONFIGURATION ENDS HERE */
  
  const PAGE_TO_SLUG = {};
  const slugs = [];
  const pages = [];
  Object.keys(SLUG_TO_PAGE).forEach(slug => {
    const page = SLUG_TO_PAGE[slug];
    slugs.push(slug);
    pages.push(page);
    PAGE_TO_SLUG[page] = slug;
  });
  
  addEventListener('fetch', event => {
    event.respondWith(fetchAndApply(event.request));
  });

  function generateSitemap() {
    let sitemap = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    slugs.forEach(
      (slug) =>
        (sitemap +=
          '<url><loc>https://' + MY_DOMAIN + '/' + slug + '</loc></url>')
    );
    sitemap += '</urlset>';
    return sitemap;
  }
  
  const corsHeaders = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, HEAD, POST, PUT, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type',
  };
  
  function handleOptions(request) {
    if (request.headers.get('Origin') !== null &&
      request.headers.get('Access-Control-Request-Method') !== null &&
      request.headers.get('Access-Control-Request-Headers') !== null) {
      // Handle CORS pre-flight request.
      return new Response(null, {
        headers: corsHeaders
      });
    } else {
      // Handle standard OPTIONS request.
      return new Response(null, {
        headers: {
          'Allow': 'GET, HEAD, POST, PUT, OPTIONS',
        }
      });
    }
  }
  
  async function fetchAndApply(request) {
    if (request.method === 'OPTIONS') {
      return handleOptions(request);
    }
    let url = new URL(request.url);
    if (url.pathname === '/robots.txt') {
      return new Response('Sitemap: https://' + MY_DOMAIN + '/sitemap.xml');
    }
    if (url.pathname === '/sitemap.xml') {
      let response = new Response(generateSitemap());
      response.headers.set('content-type', 'application/xml');
      return response;
    }
    const notionUrl = 'https://www.notion.so' + url.pathname;
    let response;
    if (url.pathname.startsWith('/app') && url.pathname.endsWith('js')) {
      response = await fetch(notionUrl);
      let body = await response.text();
      response = new Response(body.replace(/www.notion.so/g, MY_DOMAIN).replace(/notion.so/g, MY_DOMAIN), response);
      response.headers.set('Content-Type', 'application/x-javascript');
    } else if ((url.pathname.startsWith('/api'))) {
      // Forward API
      response = await fetch(notionUrl, {
        body: request.body,
        headers: {
          'content-type': 'application/json;charset=UTF-8',
          'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'
        },
        method: 'POST',
      });
      response = new Response(response.body, response);
      response.headers.set('Access-Control-Allow-Origin', '*');
    } else if (slugs.indexOf(url.pathname.slice(1)) > -1) {
      const pageId = SLUG_TO_PAGE[url.pathname.slice(1)];
      return Response.redirect('https://' + MY_DOMAIN + '/' + pageId, 301);
    } else {
      response = await fetch(notionUrl, {
        body: request.body,
        headers: request.headers,
        method: request.method,
      });
      response = new Response(response.body, response);
      response.headers.delete('Content-Security-Policy');
      response.headers.delete('X-Content-Security-Policy');
    }
  
    return appendJavascript(response, SLUG_TO_PAGE);
  }
  
  class MetaRewriter {
    element(element) {
      if (PAGE_TITLE !== '') {
        if (element.getAttribute('property') === 'og:title'
          || element.getAttribute('name') === 'twitter:title') {
          element.setAttribute('content', PAGE_TITLE);
        }
        if (element.tagName === 'title') {
          element.setInnerContent(PAGE_TITLE);
        }
      }
      if (PAGE_DESCRIPTION !== '') {
        if (element.getAttribute('name') === 'description'
          || element.getAttribute('property') === 'og:description'
          || element.getAttribute('name') === 'twitter:description') {
          element.setAttribute('content', PAGE_DESCRIPTION);
        }
      }
      if (element.getAttribute('property') === 'og:url'
        || element.getAttribute('name') === 'twitter:url') {
        element.setAttribute('content', MY_DOMAIN);
      }
      if (element.getAttribute('name') === 'apple-itunes-app') {
        element.remove();
      }
    }
  }
  
  class HeadRewriter {
    element(element) {
      if (GOOGLE_FONT !== '') {
        element.append(`<link href="https://fonts.font.im/css?family=${GOOGLE_FONT.replace(' ', '+')}:Regular,Bold,Italic&display=swap" rel="stylesheet">
        <style>* { font-family: "${GOOGLE_FONT}" !important; }</style>`, {
         html: true
        });
      }
      element.append(`<style>
      div.notion-topbar > div > div:nth-child(3) { display: none !important; }
      div.notion-topbar > div > div:nth-child(4) { display: none !important; }
      div.notion-topbar > div > div:nth-child(5) { display: none !important; }
      div.notion-topbar > div > div:nth-child(6) { display: none !important; }
      div.notion-topbar-mobile > div:nth-child(3) { display: none !important; }
      div.notion-topbar-mobile > div:nth-child(4) { display: none !important; }
      </style>`, {
        html: true
      })
    }
  }
  
  class BodyRewriter {
    constructor(SLUG_TO_PAGE) {
      this.SLUG_TO_PAGE = SLUG_TO_PAGE;
    }
    element(element) {
      element.append(`<div style="display:none">Powered by <a href="http://notion.afuture.me">afuture</a></div>
      <script>
      const SLUG_TO_PAGE = ${JSON.stringify(this.SLUG_TO_PAGE)};
      const PAGE_TO_SLUG = {};
      const slugs = [];
      const pages = [];
      let redirected = false;
      Object.keys(SLUG_TO_PAGE).forEach(slug => {
        const page = SLUG_TO_PAGE[slug];
        slugs.push(slug);
        pages.push(page);
        PAGE_TO_SLUG[page] = slug;
      });
      function getPage() {
        return location.pathname.slice(-32);
      }
      function getSlug() {
        return location.pathname.slice(1);
      }
      function updateSlug() {
        const slug = PAGE_TO_SLUG[getPage()];
        if (slug != null) {
          history.replaceState(history.state, '', '/' + slug);
        }
      }
      const observer = new MutationObserver(function() {
        if (redirected) return;
        const nav = document.querySelector('.notion-topbar');
        const mobileNav = document.querySelector('.notion-topbar-mobile');
        if (nav && nav.firstChild && nav.firstChild.firstChild
          || mobileNav && mobileNav.firstChild) {
          redirected = true;
          updateSlug();
          const onpopstate = window.onpopstate;
          window.onpopstate = function() {
            if (slugs.includes(getSlug())) {
              const page = SLUG_TO_PAGE[getSlug()];
              if (page) {
                history.replaceState(history.state, 'bypass', '/' + page);
              }
            }
            onpopstate.apply(this, [].slice.call(arguments));
            updateSlug();
          };
        }
      });
      observer.observe(document.querySelector('#notion-app'), {
        childList: true,
        subtree: true,
      });
      const replaceState = window.history.replaceState;
      window.history.replaceState = function(state) {
        if (arguments[1] !== 'bypass' && slugs.includes(getSlug())) return;
        return replaceState.apply(window.history, arguments);
      };
      const pushState = window.history.pushState;
      window.history.pushState = function(state) {
        const dest = new URL(location.protocol + location.host + arguments[2]);
        const id = dest.pathname.slice(-32);
        if (pages.includes(id)) {
          arguments[2] = '/' + PAGE_TO_SLUG[id];
        }
        return pushState.apply(window.history, arguments);
      };
      const open = window.XMLHttpRequest.prototype.open;
      window.XMLHttpRequest.prototype.open = function() {
        arguments[1] = arguments[1].replace('${MY_DOMAIN}', 'www.notion.so');
        return open.apply(this, [].slice.call(arguments));
      };
    </script>${CUSTOM_SCRIPT}`, {
        html: true
      });
    }
  }
  
  async function appendJavascript(res, SLUG_TO_PAGE) {
    return new HTMLRewriter()
      .on('title', new MetaRewriter())
      .on('meta', new MetaRewriter())
      .on('head', new HeadRewriter())
      .on('body', new BodyRewriter(SLUG_TO_PAGE))
      .transform(res);
  }
Article Details