小编Bal*_*rol的帖子

Scrapy - 无声地放下一个物品

我正在使用Scrapy抓取几个可能共享冗余信息的网站.

对于我抓取的每个页面,我将页面的URL,标题和html代码存储到mongoDB中.我想避免数据库中的重复,因此,我实现了一个管道,以检查是否已经存储了类似的项目.在这种情况下,我提出DropItem异常.

我的问题是,每当我通过raison DropItem异常删除项目时,Scrapy会将项目的全部内容显示在日志(stdout或文件)中.由于我正在提取每个已删除页面的整个HTML代码,因此在丢弃的情况下,整个HTML代码将显示在日志中.

如果没有显示内容,我怎么能默默地删除项目?

感谢您的时间!

class DatabaseStorage(object):
    """ Pipeline in charge of database storage.

    The 'whole' item (with HTML and text) will be stored in mongoDB.
    """

    def __init__(self):
        self.mongo = MongoConnector().collection

    def process_item(self, item, spider):
        """ Method in charge of item valdation and processing. """
        if item['html'] and item['title'] and item['url']:
            # insert item in mongo if not already present
            if self.mongo.find_one({'title': item['title']}):
                raise DropItem('Item already in db')
            else:
                self.mongo.insert(dict(item))
                log.msg("Item %s scraped" % item['title'], …
Run Code Online (Sandbox Code Playgroud)

python scrapy

22
推荐指数
3
解决办法
5199
查看次数

如何使用setup.py安装托管在私有PyPI中的软件包?

我正在尝试setup.py为私有项目编写安装文件,该项目具有公共和私有依赖项.公共的托管在PyPI上,而私有托管在运行simplepypi的服务器上.

我希望在安装过程中解析和获取公共和私有依赖项.

因此我将依赖项添加到setup.py:

setup(
    ...
    install_requires = [
        # public dependencies
        'argparse==1.2.1',
        'beautifulsoup4==4.1.3',
        'lxml==3.1.0',
        'mongoengine==0.8.2',
        'pymongo==2.5.2',
        'requests==1.1.0',
        'Cython==0.18',
        # private dependencies
        'myprivatepackage1',
        'myprivatepackage2'
    ],
    dependency_links=['http://pypi.myserver.com/packages'],
    ...
)
Run Code Online (Sandbox Code Playgroud)

我使用命令构建包tarball并使用python setup.py sdist激活的virtualenv安装它pip install --verbose path/to/tarball.tar.gz.

但是,pip日志行没有在任何地方提到我的私有PyPI服务器,并且https://pypi.python.org/simple/似乎已被查询两次.

Running setup.py egg_info for package from file:///home/b/code/mapado/mypackage/dist/mypackage-0.5.1.tar.gz
    running egg_info
    creating pip-egg-info/mypackage.egg-info
    writing requirements to pip-egg-info/mypackage.egg-info/requires.txt
    writing pip-egg-info/mypackage.egg-info/PKG-INFO
    writing top-level names to pip-egg-info/mypackage.egg-info/top_level.txt
    writing dependency_links to pip-egg-info/mypackage.egg-info/dependency_links.txt
    writing manifest file 'pip-egg-info/mypackage.egg-info/SOURCES.txt'
    warning: manifest_maker: standard file …
Run Code Online (Sandbox Code Playgroud)

python setuptools pypi

20
推荐指数
1
解决办法
3万
查看次数

Mongoengine - 如何执行"保存新项目或增加计数器"操作?

我在一个网络抓取项目中使用MongoEngine.我想跟踪我在所有抓取的网页上遇到的所有图像.

为此,我存储图像srcURL和图像遇到的次数.

MongoEngine模型定义如下:

class ImagesUrl(Document):
    """ Model representing images encountered during web-scraping.

    When an image is encountered on a web-page during scraping,
    we store its url and the number of times it has been
    seen (default counter value is 1).
    If the image had been seen before, we do not insert a new document
    in collection, but merely increment the corresponding counter value.

    """

    # The url of the image. There cannot be any duplicate.
    src = URLField(required=True, …
Run Code Online (Sandbox Code Playgroud)

python mongodb mongoengine

6
推荐指数
1
解决办法
1589
查看次数

如何添加 kubernetes liveness probe 来检查进程是否存活

我有一个在 Ubuntu 容器内运行的进程,如果该进程被终止,我想重新部署该容器。我在容器规范中添加了以下活性探针

  livenessProbe:
    exec:
     command:
     - ps -ef | grep my_process_name
    initialDelaySeconds: 120
    periodSeconds: 30
Run Code Online (Sandbox Code Playgroud)

然而这不起作用。当我做一个kubectl describe pods <pod_id>我得到以下事件。

  1h    6m      20      {kubelet k8s-agent-71e8d996-0}        spec.containers{my_process_name}       Warning Unhealthy       Liveness       probe failed: rpc error: code = 13 desc = invalid header field value "oci runtime error: exec failed: container_linux.go:247: starting container process caused \"exec: \\\"ps -ef | grep my_process_name\\\": executable file not found in $PATH\"\n"
Run Code Online (Sandbox Code Playgroud)

它不断重新部署容器。如果我猛击容器并执行“ps -ef”,它会起作用,但这不是使用活性探针检查进程是否正在运行的好方法?谢谢。

kubernetes

6
推荐指数
2
解决办法
4361
查看次数

预取列序列SQLAlchemy

我的模型非常复杂,我正在尝试从现有存储过程中获取逻辑并将它们转换为SQLAlchemy(出于可移植性的原因).

我对未提交的数据感到困惑.

我有user表:1d,名字我有status表:id,名字我有user_statuses表:id,user_id,status_id,from_dt,to_dt

现在,我需要在单个事务中填充所有这些表,否则会失败.问题:

user = User(name = 'Test')
status = Status(name = 'Active')
db.session.add(user)
db.session.add(status)

# Oooopa! This is where it fails
user_session = UserStatuses(user_id=user.id, status_id=status.id, datetime.utcnow(), datetime(9999,01,01,00,00,00))
# both user.id and status.id = None as it's uncommited!
Run Code Online (Sandbox Code Playgroud)

本质上,我需要能够访问没有显式SQL的表序列.为什么?为了便携性.目前我使用PGSQL并且可以这样做:

class User(Base):
    ....
    @staticmethod
    def prefetch_id():
        db.session.execute("SELECT NEXTVAL('user_id_seq');").scalar()
Run Code Online (Sandbox Code Playgroud)

将引擎更改为MySQL&BANG!申请破了.

关于如何做到这一点的任何想法?请记住,这可能是一个非常高的交易应用程序,一次被成千上万的用户访问

python mysql sqlalchemy postgresql-9.2

5
推荐指数
2
解决办法
3830
查看次数

MongoEngine - 通过 id 从 ListField 中提取引用

我想从 a 中删除一些引用ListField(ReferenceField),完全基于它们的值。

我将有关图像的信息存储在以下模型中:

class ImageUrl(Document):
    src = UrlField()
    counter = IntField()
    deleted = BooleanField()
Run Code Online (Sandbox Code Playgroud)

我们将id页面上遇到的图像的s存储在一个EmbeddedDocument被调用的s 中Webpage

class Webpage(EmbeddedDocument):
    image_list = ListField(ReferenceField(ImageUrl))
    ...
Run Code Online (Sandbox Code Playgroud)

最后,将Website模型嵌入到RawData模型中:

class RawData(Document):
    ...
    webpage = EmbeddedDocumentField(Webpage)
Run Code Online (Sandbox Code Playgroud)

我想ImageUrlRawData记录中删除对记录的引用,基于它们的一些属性(例如:计数器值超过 1),然后将deleted这些ImageUrl记录的属性设置为True.

我正在做:

images = ImageUrl.objects((Q(deleted=False) & Q(counter__gt=1)).all()
for image in images:
    # all RadData records containing the image in their image list
    for rdata in RawData.objects(webpage__image_list__in=[image.id]:
        # …
Run Code Online (Sandbox Code Playgroud)

python mongodb mongoengine

4
推荐指数
1
解决办法
4052
查看次数

我可以将 vm 放入另一个资源组而不是availabilitySet 吗?

我想将每个 VM 保存在单独的资源组中,以便于生命周期管理。我有一个包含 n 个 VLM 的集群。

因此,我为公共 IP、负载均衡器等常见事物创建了一个资源组,并将 availabilitySet 声明放入其中,因为它也必须在 VM 之间共享。然后我在单独的资源组中创建 VM 并使用“availabilitySet”引用availabilitySet:{“id”:“[resourceId('Microsoft.Compute/availabilitySets',variables('availabilitySetName'))]”},原因是'availabilitySetName'被定义为。

当我部署我的模板时,我收到一条错误消息

{"error":{"code":"BadRequest","message":"资源引用 ID 中的实体 resourceGroupName /subscriptions/a719381f-1fa0-4b06-8e29-ad6ea7d3c90b/resourceGroups/TB_PIP_OPSRV_UAT/providers/Microsoft.Compute/availability tb_avlbs_opsrv_uat 无效。"}}

我仔细检查了资源和可用性集名称是否正确指定。

这是否意味着我不能将一个集合放在与 VM 不同的资源组中?

azure azure-virtual-machine azure-resource-manager

3
推荐指数
1
解决办法
2101
查看次数

将文本功能名称链接到其tfidf值

我正在使用scikit-learn从一个"文字袋"文本中提取文本特征(文本在单个单词上标记).为此,我使用TfidfVectorizer来减轻非常频繁的单词的重量(即:"a","the"等).

text = 'Some text, with a lot of words...'
tfidf_vectorizer = TfidfVectorizer(
    min_df=1,  # min count for relevant vocabulary
    max_features=4000,  # maximum number of features
    strip_accents='unicode',  # replace all accented unicode char
    # by their corresponding  ASCII char
    analyzer='word',  # features made of words
    token_pattern=r'\w{4,}',  # tokenize only words of 4+ chars
    ngram_range=(1, 1),  # features made of a single tokens
    use_idf=True,  # enable inverse-document-frequency reweighting
    smooth_idf=True,  # prevents zero division for unseen words
    sublinear_tf=False)

# vectorize …
Run Code Online (Sandbox Code Playgroud)

python text-processing machine-learning scikit-learn

2
推荐指数
1
解决办法
4561
查看次数