From f06e95537e69707c96911a4b649f4ace1c212905 Mon Sep 17 00:00:00 2001 From: Marvin Zhang Date: Tue, 2 Jul 2019 21:01:37 +0800 Subject: [PATCH 1/9] added sinastock spider --- spiders/sinastock/scrapy.cfg | 11 ++ spiders/sinastock/sinastock/__init__.py | 0 spiders/sinastock/sinastock/items.py | 19 ++++ spiders/sinastock/sinastock/middlewares.py | 103 ++++++++++++++++++ spiders/sinastock/sinastock/pipelines.py | 25 +++++ spiders/sinastock/sinastock/settings.py | 89 +++++++++++++++ .../sinastock/sinastock/spiders/__init__.py | 4 + .../sinastock/spiders/sinastock_spider.py | 57 ++++++++++ 8 files changed, 308 insertions(+) create mode 100644 spiders/sinastock/scrapy.cfg create mode 100644 spiders/sinastock/sinastock/__init__.py create mode 100644 spiders/sinastock/sinastock/items.py create mode 100644 spiders/sinastock/sinastock/middlewares.py create mode 100644 spiders/sinastock/sinastock/pipelines.py create mode 100644 spiders/sinastock/sinastock/settings.py create mode 100644 spiders/sinastock/sinastock/spiders/__init__.py create mode 100644 spiders/sinastock/sinastock/spiders/sinastock_spider.py diff --git a/spiders/sinastock/scrapy.cfg b/spiders/sinastock/scrapy.cfg new file mode 100644 index 000000000..4969ad963 --- /dev/null +++ b/spiders/sinastock/scrapy.cfg @@ -0,0 +1,11 @@ +# Automatically created by: scrapy startproject +# +# For more information about the [deploy] section see: +# https://scrapyd.readthedocs.io/en/latest/deploy.html + +[settings] +default = sinastock.settings + +[deploy] +#url = http://localhost:6800/ +project = sinastock diff --git a/spiders/sinastock/sinastock/__init__.py b/spiders/sinastock/sinastock/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/spiders/sinastock/sinastock/items.py b/spiders/sinastock/sinastock/items.py new file mode 100644 index 000000000..5c0e6570a --- /dev/null +++ b/spiders/sinastock/sinastock/items.py @@ -0,0 +1,19 @@ +# -*- coding: utf-8 -*- + +# Define here the models for your scraped items +# +# See documentation in: +# https://doc.scrapy.org/en/latest/topics/items.html + +import scrapy + + +class NewsItem(scrapy.Item): + # define the fields for your item here like: + _id = scrapy.Field() + title = scrapy.Field() + ts_str = scrapy.Field() + ts = scrapy.Field() + url = scrapy.Field() + text = scrapy.Field() + task_id = scrapy.Field() diff --git a/spiders/sinastock/sinastock/middlewares.py b/spiders/sinastock/sinastock/middlewares.py new file mode 100644 index 000000000..912b5e57f --- /dev/null +++ b/spiders/sinastock/sinastock/middlewares.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- + +# Define here the models for your spider middleware +# +# See documentation in: +# https://doc.scrapy.org/en/latest/topics/spider-middleware.html + +from scrapy import signals + + +class SinastockSpiderMiddleware(object): + # Not all methods need to be defined. If a method is not defined, + # scrapy acts as if the spider middleware does not modify the + # passed objects. + + @classmethod + def from_crawler(cls, crawler): + # This method is used by Scrapy to create your spiders. + s = cls() + crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) + return s + + def process_spider_input(self, response, spider): + # Called for each response that goes through the spider + # middleware and into the spider. + + # Should return None or raise an exception. + return None + + def process_spider_output(self, response, result, spider): + # Called with the results returned from the Spider, after + # it has processed the response. + + # Must return an iterable of Request, dict or Item objects. + for i in result: + yield i + + def process_spider_exception(self, response, exception, spider): + # Called when a spider or process_spider_input() method + # (from other spider middleware) raises an exception. + + # Should return either None or an iterable of Response, dict + # or Item objects. + pass + + def process_start_requests(self, start_requests, spider): + # Called with the start requests of the spider, and works + # similarly to the process_spider_output() method, except + # that it doesn’t have a response associated. + + # Must return only requests (not items). + for r in start_requests: + yield r + + def spider_opened(self, spider): + spider.logger.info('Spider opened: %s' % spider.name) + + +class SinastockDownloaderMiddleware(object): + # Not all methods need to be defined. If a method is not defined, + # scrapy acts as if the downloader middleware does not modify the + # passed objects. + + @classmethod + def from_crawler(cls, crawler): + # This method is used by Scrapy to create your spiders. + s = cls() + crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) + return s + + def process_request(self, request, spider): + # Called for each request that goes through the downloader + # middleware. + + # Must either: + # - return None: continue processing this request + # - or return a Response object + # - or return a Request object + # - or raise IgnoreRequest: process_exception() methods of + # installed downloader middleware will be called + return None + + def process_response(self, request, response, spider): + # Called with the response returned from the downloader. + + # Must either; + # - return a Response object + # - return a Request object + # - or raise IgnoreRequest + return response + + def process_exception(self, request, exception, spider): + # Called when a download handler or a process_request() + # (from other downloader middleware) raises an exception. + + # Must either: + # - return None: continue processing this exception + # - return a Response object: stops process_exception() chain + # - return a Request object: stops process_exception() chain + pass + + def spider_opened(self, spider): + spider.logger.info('Spider opened: %s' % spider.name) diff --git a/spiders/sinastock/sinastock/pipelines.py b/spiders/sinastock/sinastock/pipelines.py new file mode 100644 index 000000000..ba1996fd9 --- /dev/null +++ b/spiders/sinastock/sinastock/pipelines.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- + +# Define your item pipelines here +# +# Don't forget to add your pipeline to the ITEM_PIPELINES setting +# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html +import os + +from pymongo import MongoClient + + +class SinastockPipeline(object): + mongo = MongoClient( + host=os.environ.get('MONGO_HOST') or 'localhost', + port=int(os.environ.get('MONGO_PORT') or 27017) + ) + db = mongo[os.environ.get('MONGO_DB') or 'crawlab_test'] + col = db.get_collection(os.environ.get('CRAWLAB_COLLECTION') or 'stock_news') + + def process_item(self, item, spider): + item['task_id'] = os.environ.get('CRAWLAB_TASK_ID') + item['_id'] = item['url'] + if self.col.find_one({'_id': item['_id']}) is None: + self.col.save(item) + return item diff --git a/spiders/sinastock/sinastock/settings.py b/spiders/sinastock/sinastock/settings.py new file mode 100644 index 000000000..c63c2eb54 --- /dev/null +++ b/spiders/sinastock/sinastock/settings.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- + +# Scrapy settings for sinastock project +# +# For simplicity, this file contains only settings considered important or +# commonly used. You can find more settings consulting the documentation: +# +# https://doc.scrapy.org/en/latest/topics/settings.html +# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html +# https://doc.scrapy.org/en/latest/topics/spider-middleware.html + +BOT_NAME = 'sinastock' + +SPIDER_MODULES = ['sinastock.spiders'] +NEWSPIDER_MODULE = 'sinastock.spiders' + +# Crawl responsibly by identifying yourself (and your website) on the user-agent +# USER_AGENT = 'sinastock (+http://www.yourdomain.com)' + +# Obey robots.txt rules +ROBOTSTXT_OBEY = True + +# Configure maximum concurrent requests performed by Scrapy (default: 16) +# CONCURRENT_REQUESTS = 32 + +# Configure a delay for requests for the same website (default: 0) +# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay +# See also autothrottle settings and docs +# DOWNLOAD_DELAY = 3 +# The download delay setting will honor only one of: +# CONCURRENT_REQUESTS_PER_DOMAIN = 16 +# CONCURRENT_REQUESTS_PER_IP = 16 + +# Disable cookies (enabled by default) +# COOKIES_ENABLED = False + +# Disable Telnet Console (enabled by default) +# TELNETCONSOLE_ENABLED = False + +# Override the default request headers: +# DEFAULT_REQUEST_HEADERS = { +# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', +# 'Accept-Language': 'en', +# } + +# Enable or disable spider middlewares +# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html +# SPIDER_MIDDLEWARES = { +# 'sinastock.middlewares.SinastockSpiderMiddleware': 543, +# } + +# Enable or disable downloader middlewares +# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html +# DOWNLOADER_MIDDLEWARES = { +# 'sinastock.middlewares.SinastockDownloaderMiddleware': 543, +# } + +# Enable or disable extensions +# See https://doc.scrapy.org/en/latest/topics/extensions.html +# EXTENSIONS = { +# 'scrapy.extensions.telnet.TelnetConsole': None, +# } + +# Configure item pipelines +# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html +ITEM_PIPELINES = { + 'sinastock.pipelines.SinastockPipeline': 300, +} + +# Enable and configure the AutoThrottle extension (disabled by default) +# See https://doc.scrapy.org/en/latest/topics/autothrottle.html +# AUTOTHROTTLE_ENABLED = True +# The initial download delay +# AUTOTHROTTLE_START_DELAY = 5 +# The maximum download delay to be set in case of high latencies +# AUTOTHROTTLE_MAX_DELAY = 60 +# The average number of requests Scrapy should be sending in parallel to +# each remote server +# AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 +# Enable showing throttling stats for every response received: +# AUTOTHROTTLE_DEBUG = False + +# Enable and configure HTTP caching (disabled by default) +# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings +# HTTPCACHE_ENABLED = True +# HTTPCACHE_EXPIRATION_SECS = 0 +# HTTPCACHE_DIR = 'httpcache' +# HTTPCACHE_IGNORE_HTTP_CODES = [] +# HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' diff --git a/spiders/sinastock/sinastock/spiders/__init__.py b/spiders/sinastock/sinastock/spiders/__init__.py new file mode 100644 index 000000000..ebd689ac5 --- /dev/null +++ b/spiders/sinastock/sinastock/spiders/__init__.py @@ -0,0 +1,4 @@ +# This package will contain the spiders of your Scrapy project +# +# Please refer to the documentation for information on how to create and manage +# your spiders. diff --git a/spiders/sinastock/sinastock/spiders/sinastock_spider.py b/spiders/sinastock/sinastock/spiders/sinastock_spider.py new file mode 100644 index 000000000..6b3051b69 --- /dev/null +++ b/spiders/sinastock/sinastock/spiders/sinastock_spider.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +import os +import re +from datetime import datetime + +import scrapy +from pymongo import MongoClient + +from sinastock.items import NewsItem + + +class SinastockSpiderSpider(scrapy.Spider): + name = 'sinastock_spider' + allowed_domains = ['finance.sina.com.cn'] + mongo = MongoClient( + host=os.environ.get('MONGO_HOST') or 'localhost', + port=int(os.environ.get('MONGO_PORT') or 27017) + ) + db = mongo[os.environ.get('MONGO_DB') or 'crawlab_test'] + col = db.get_collection(os.environ.get('CRAWLAB_COLLECTION') or 'stock_news') + + def start_requests(self): + col = self.db['stocks'] + for s in col.find({}): + code, ex = s['ts_code'].split('.') + for i in range(10): + url = f'http://vip.stock.finance.sina.com.cn/corp/view/vCB_AllNewsStock.php?symbol={ex.lower()}{code}&Page={i + 1}' + yield scrapy.Request( + url=url, + callback=self.parse + ) + + def parse(self, response): + for a in response.css('.datelist > ul > a'): + url = a.css('a::attr("href")').extract_first() + item = NewsItem( + title=a.css('a::text').extract_first(), + url=url, + ) + yield scrapy.Request( + url=url, + callback=self.parse_detail, + meta={'item': item} + ) + + def parse_detail(self, response): + item = response.meta['item'] + text = response.css('#artibody').extract_first() + pre = re.compile('>(.*?)<') + text = ''.join(pre.findall(text)) + item['text'] = text.replace('\u3000', '') + item['ts_str'] = response.css('.date::text').extract_first() + if item['text'] is None or item['ts_str'] is None: + pass + else: + item['ts'] = datetime.strptime(item['ts_str'], '%Y年%m月%d日 %H:%M') + yield item From 541f17aa6128c532622ef47b15c6390f3ddb36c8 Mon Sep 17 00:00:00 2001 From: Marvin Zhang Date: Thu, 4 Jul 2019 18:21:08 +0800 Subject: [PATCH 2/9] updated sinastock_spider --- spiders/sinastock/sinastock/items.py | 2 ++ spiders/sinastock/sinastock/pipelines.py | 7 +++++-- spiders/sinastock/sinastock/spiders/sinastock_spider.py | 5 ++++- spiders/xueqiu/xueqiu/items.py | 3 +++ spiders/xueqiu/xueqiu/pipelines.py | 8 ++++++-- spiders/xueqiu/xueqiu/spiders/xueqiu_spider.py | 5 ++++- 6 files changed, 24 insertions(+), 6 deletions(-) diff --git a/spiders/sinastock/sinastock/items.py b/spiders/sinastock/sinastock/items.py index 5c0e6570a..6e3e5d8ea 100644 --- a/spiders/sinastock/sinastock/items.py +++ b/spiders/sinastock/sinastock/items.py @@ -17,3 +17,5 @@ class NewsItem(scrapy.Item): url = scrapy.Field() text = scrapy.Field() task_id = scrapy.Field() + source = scrapy.Field() + stocks = scrapy.Field() diff --git a/spiders/sinastock/sinastock/pipelines.py b/spiders/sinastock/sinastock/pipelines.py index ba1996fd9..e666c50d1 100644 --- a/spiders/sinastock/sinastock/pipelines.py +++ b/spiders/sinastock/sinastock/pipelines.py @@ -17,9 +17,12 @@ class SinastockPipeline(object): db = mongo[os.environ.get('MONGO_DB') or 'crawlab_test'] col = db.get_collection(os.environ.get('CRAWLAB_COLLECTION') or 'stock_news') + # create indexes + col.create_index('stocks') + col.create_index('url') + def process_item(self, item, spider): item['task_id'] = os.environ.get('CRAWLAB_TASK_ID') - item['_id'] = item['url'] - if self.col.find_one({'_id': item['_id']}) is None: + if self.col.find_one({'url': item['url']}) is None: self.col.save(item) return item diff --git a/spiders/sinastock/sinastock/spiders/sinastock_spider.py b/spiders/sinastock/sinastock/spiders/sinastock_spider.py index 6b3051b69..9d258e6c7 100644 --- a/spiders/sinastock/sinastock/spiders/sinastock_spider.py +++ b/spiders/sinastock/sinastock/spiders/sinastock_spider.py @@ -27,7 +27,8 @@ def start_requests(self): url = f'http://vip.stock.finance.sina.com.cn/corp/view/vCB_AllNewsStock.php?symbol={ex.lower()}{code}&Page={i + 1}' yield scrapy.Request( url=url, - callback=self.parse + callback=self.parse, + meta={'ts_code': s['ts_code']} ) def parse(self, response): @@ -36,6 +37,8 @@ def parse(self, response): item = NewsItem( title=a.css('a::text').extract_first(), url=url, + source='sina', + stocks=[response.meta['ts_code']] ) yield scrapy.Request( url=url, diff --git a/spiders/xueqiu/xueqiu/items.py b/spiders/xueqiu/xueqiu/items.py index e50e4823b..5471594df 100644 --- a/spiders/xueqiu/xueqiu/items.py +++ b/spiders/xueqiu/xueqiu/items.py @@ -14,7 +14,10 @@ class XueqiuItem(scrapy.Item): task_id = scrapy.Field() id = scrapy.Field() text = scrapy.Field() + url = scrapy.Field() target = scrapy.Field() view_count = scrapy.Field() mark = scrapy.Field() created_at = scrapy.Field() + ts = scrapy.Field() + source = scrapy.Field() diff --git a/spiders/xueqiu/xueqiu/pipelines.py b/spiders/xueqiu/xueqiu/pipelines.py index 671737725..210ce7ac5 100644 --- a/spiders/xueqiu/xueqiu/pipelines.py +++ b/spiders/xueqiu/xueqiu/pipelines.py @@ -17,9 +17,13 @@ class XueqiuPipeline(object): db = mongo[os.environ.get('MONGO_DB') or 'crawlab_test'] col = db.get_collection(os.environ.get('CRAWLAB_COLLECTION') or 'results_xueqiu') + # create indexes + col.create_index('stocks') + col.create_index('id') + col.create_index('url') + def process_item(self, item, spider): item['task_id'] = os.environ.get('CRAWLAB_TASK_ID') - item['_id'] = item['id'] - if self.col.find_one({'_id': item['_id']}) is None: + if self.col.find_one({'id': item['id']}) is None: self.col.save(item) return item diff --git a/spiders/xueqiu/xueqiu/spiders/xueqiu_spider.py b/spiders/xueqiu/xueqiu/spiders/xueqiu_spider.py index 6ccb13c09..a746e1560 100644 --- a/spiders/xueqiu/xueqiu/spiders/xueqiu_spider.py +++ b/spiders/xueqiu/xueqiu/spiders/xueqiu_spider.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- import json +from datetime import datetime from time import sleep import scrapy @@ -32,9 +33,11 @@ def parse(self, response): id=d['id'], text=d['text'], mark=d['mark'], - target=d['target'], + url=d['target'], created_at=d['created_at'], + ts=datetime.fromtimestamp(d['created_at'] / 1e3), view_count=d['view_count'], + source='xueqiu' ) yield item From 614447bd06b76d9691c1d646a9b54213d5177172 Mon Sep 17 00:00:00 2001 From: luzihang123 <526154064@qq.com> Date: Fri, 5 Jul 2019 14:50:32 +0800 Subject: [PATCH 3/9] =?UTF-8?q?=E4=BF=AE=E6=94=B9README=E9=94=99=E5=88=AB?= =?UTF-8?q?=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-zh.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README-zh.md b/README-zh.md index 048ae859b..cff9424c6 100644 --- a/README-zh.md +++ b/README-zh.md @@ -89,7 +89,7 @@ Crawlab的架构跟Celery非常相似,但是加入了包括前端、爬虫、F 任务是利用python的`subprocess`模块中的`Popen`来实现的。任务ID将以环境变量`CRAWLAB_TASK_ID`的形式存在于爬虫任务运行的进程中,并以此来关联抓取数据。 -在你的爬虫程序中,你需要将`CRAWLAB_TASK_ID`的值以`task_id`作为可以存入数据库中。这样Crawlab就直到如何将爬虫任务与抓取数据关联起来了。当前,Crawlab只支持MongoDB。 +在你的爬虫程序中,你需要将`CRAWLAB_TASK_ID`的值以`task_id`作为可以存入数据库中。这样Crawlab就知道如何将爬虫任务与抓取数据关联起来了。当前,Crawlab只支持MongoDB。 ### Scrapy From 12e99921aeb4cb112e37ebf9640edd6974f047de Mon Sep 17 00:00:00 2001 From: Marvin Zhang Date: Sun, 7 Jul 2019 09:03:02 +0800 Subject: [PATCH 4/9] updated sinastock_spider --- spiders/sinastock/sinastock/spiders/sinastock_spider.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spiders/sinastock/sinastock/spiders/sinastock_spider.py b/spiders/sinastock/sinastock/spiders/sinastock_spider.py index 9d258e6c7..95c9df86e 100644 --- a/spiders/sinastock/sinastock/spiders/sinastock_spider.py +++ b/spiders/sinastock/sinastock/spiders/sinastock_spider.py @@ -18,12 +18,13 @@ class SinastockSpiderSpider(scrapy.Spider): ) db = mongo[os.environ.get('MONGO_DB') or 'crawlab_test'] col = db.get_collection(os.environ.get('CRAWLAB_COLLECTION') or 'stock_news') + page_num = os.environ.get('PAGE_NUM') or 3 def start_requests(self): col = self.db['stocks'] for s in col.find({}): code, ex = s['ts_code'].split('.') - for i in range(10): + for i in range(self.page_num): url = f'http://vip.stock.finance.sina.com.cn/corp/view/vCB_AllNewsStock.php?symbol={ex.lower()}{code}&Page={i + 1}' yield scrapy.Request( url=url, From 2c05c720fc8fadd0fbb1752b248d321325688fbe Mon Sep 17 00:00:00 2001 From: Marvin Zhang Date: Sun, 7 Jul 2019 09:17:15 +0800 Subject: [PATCH 5/9] updated sinastock_spider --- spiders/sinastock/sinastock/spiders/sinastock_spider.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spiders/sinastock/sinastock/spiders/sinastock_spider.py b/spiders/sinastock/sinastock/spiders/sinastock_spider.py index 95c9df86e..d5cd91d67 100644 --- a/spiders/sinastock/sinastock/spiders/sinastock_spider.py +++ b/spiders/sinastock/sinastock/spiders/sinastock_spider.py @@ -18,7 +18,7 @@ class SinastockSpiderSpider(scrapy.Spider): ) db = mongo[os.environ.get('MONGO_DB') or 'crawlab_test'] col = db.get_collection(os.environ.get('CRAWLAB_COLLECTION') or 'stock_news') - page_num = os.environ.get('PAGE_NUM') or 3 + page_num = int(os.environ.get('PAGE_NUM')) or 3 def start_requests(self): col = self.db['stocks'] From d4bcc3c3fc89dfd0c0bb2cdc0039accb89159678 Mon Sep 17 00:00:00 2001 From: Marvin Zhang Date: Sun, 7 Jul 2019 09:34:02 +0800 Subject: [PATCH 6/9] updated sinastock_spider: time zone adjustment --- spiders/sinastock/sinastock/spiders/sinastock_spider.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/spiders/sinastock/sinastock/spiders/sinastock_spider.py b/spiders/sinastock/sinastock/spiders/sinastock_spider.py index d5cd91d67..6605a794c 100644 --- a/spiders/sinastock/sinastock/spiders/sinastock_spider.py +++ b/spiders/sinastock/sinastock/spiders/sinastock_spider.py @@ -5,9 +5,13 @@ import scrapy from pymongo import MongoClient +import pytz from sinastock.items import NewsItem +# 时区 +tz = pytz.timezone('Asia/Shanghai') + class SinastockSpiderSpider(scrapy.Spider): name = 'sinastock_spider' @@ -57,5 +61,7 @@ def parse_detail(self, response): if item['text'] is None or item['ts_str'] is None: pass else: - item['ts'] = datetime.strptime(item['ts_str'], '%Y年%m月%d日 %H:%M') + ts = datetime.strptime(item['ts_str'], '%Y年%m月%d日 %H:%M') + ts = tz.localize(ts) + item['ts'] = ts yield item From 9f9e60336540c042c63296e815eed91c8a27ba8c Mon Sep 17 00:00:00 2001 From: Marvin Zhang Date: Sun, 7 Jul 2019 16:16:48 +0800 Subject: [PATCH 7/9] fixed https://github.com/tikazyq/crawlab/issues/78 --- crawlab/app.py | 2 +- crawlab/requirements.txt | 1 + crawlab/tasks/scheduler.py | 18 ++++++++++++++++-- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/crawlab/app.py b/crawlab/app.py index 493c9bedd..484e92349 100644 --- a/crawlab/app.py +++ b/crawlab/app.py @@ -103,4 +103,4 @@ def update_nodes_status_online(event): if __name__ == '__main__': # run app instance - app.run(host=FLASK_HOST, port=FLASK_PORT, threaded=True) + app.run(host=FLASK_HOST, port=FLASK_PORT) diff --git a/crawlab/requirements.txt b/crawlab/requirements.txt index 67c8d0db6..282c4cc22 100644 --- a/crawlab/requirements.txt +++ b/crawlab/requirements.txt @@ -14,3 +14,4 @@ eventlet Celery Flower redis +gunicorn diff --git a/crawlab/tasks/scheduler.py b/crawlab/tasks/scheduler.py index 16597f671..b9fcb1401 100644 --- a/crawlab/tasks/scheduler.py +++ b/crawlab/tasks/scheduler.py @@ -1,3 +1,6 @@ +import atexit +import fcntl + import requests from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.jobstores.mongodb import MongoDBJobStore @@ -65,8 +68,19 @@ def update(self): print(f'running: {self.scheduler.running}') def run(self): - self.update() - self.scheduler.start() + f = open("scheduler.lock", "wb") + try: + fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) + self.update() + self.scheduler.start() + except: + pass + + def unlock(): + fcntl.flock(f, fcntl.LOCK_UN) + f.close() + + atexit.register(unlock) scheduler = Scheduler() From ba704b5a471c5b1faba95ce48596f1c8093b5415 Mon Sep 17 00:00:00 2001 From: Marvin Zhang Date: Sun, 7 Jul 2019 16:17:08 +0800 Subject: [PATCH 8/9] fixed https://github.com/tikazyq/crawlab/issues/78 --- docker_init.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docker_init.sh b/docker_init.sh index 7298613c5..23d9cfa4a 100755 --- a/docker_init.sh +++ b/docker_init.sh @@ -1,12 +1,13 @@ #!/bin/sh case $1 in master) - cd /opt/crawlab/frontend \ + cd $WORK_DIR/frontend \ && npm run build:prod \ && service nginx start python $WORK_DIR/crawlab/flower.py >> /opt/crawlab/flower.log 2>&1 & python $WORK_DIR/crawlab/worker.py >> /opt/crawlab/worker.log 2>&1 & - python $WORK_DIR/crawlab/app.py + cd $WORK_DIR/crawlab \ + && gunicorn --log-level=DEBUG -b 0.0.0.0 -w 8 $WORK_DIR/crawlab/app:app ;; worker) python $WORK_DIR/crawlab/app.py >> /opt/crawlab/app.log 2>&1 & From 211fc134b150bd44e231517244049fc7b11252b6 Mon Sep 17 00:00:00 2001 From: Marvin Zhang Date: Sun, 7 Jul 2019 16:30:37 +0800 Subject: [PATCH 9/9] updated docker_init.sh --- docker_init.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker_init.sh b/docker_init.sh index 23d9cfa4a..2404580cf 100755 --- a/docker_init.sh +++ b/docker_init.sh @@ -7,7 +7,7 @@ case $1 in python $WORK_DIR/crawlab/flower.py >> /opt/crawlab/flower.log 2>&1 & python $WORK_DIR/crawlab/worker.py >> /opt/crawlab/worker.log 2>&1 & cd $WORK_DIR/crawlab \ - && gunicorn --log-level=DEBUG -b 0.0.0.0 -w 8 $WORK_DIR/crawlab/app:app + && gunicorn --log-level=DEBUG -b 0.0.0.0 -w 8 app:app ;; worker) python $WORK_DIR/crawlab/app.py >> /opt/crawlab/app.log 2>&1 &