index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
3,714
mrpal39/ev_code
refs/heads/master
/awssam/ideablog/core/admin.py
from django.contrib import admin from .models import Products,feeds,MyModel,Post # Register your models here. admin.site.register(Products) admin.site.register(feeds) admin.site.register(MyModel) admin.site.register(Post)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,715
mrpal39/ev_code
refs/heads/master
/awssam/django-blog/src/blog/admin.py
from django.contrib import admin # Register your models here. from blog.models import Tag, Article, Category @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): date_hierarchy = 'date_time' list_display = ('title', 'category', 'author', 'date_time', 'view') list_filter = ('category', 'author') filter_horizontal = ('tag',) @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): pass @admin.register(Tag) class TagAdmin(admin.ModelAdmin): pass
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,716
mrpal39/ev_code
refs/heads/master
/myapi/fullfeblog/blog/blog_tags.py
from django import template from django.db.models import Q from django.conf import settings from django.template.defaultfilters import stringfilter from django.utils.safestring import mark_safe import random from django.urls import reverse # from blog.models import Article, Category, Tag, Links, SideBar, LinkShowType from django.utils.encoding import force_text from django.shortcuts import get_object_or_404 import hashlib import urllib # from comments.models import Comment from DjangoBlog.utils import cache_decorator, cache from django.contrib.auth import get_user_model from oauth.models import OAuthUser from DjangoBlog.utils import get_current_site import logging logger = logging.getLogger(__name__) register = template.Library() @register.simple_tag def timeformat(data): try: return data.strftime(settings.TIME_FORMAT) # print(data.strftime(settings.TIME_FORMAT)) # return "ddd" except Exception as e: logger.error(e) return "" @register.simple_tag def datetimeformat(data): try: return data.strftime(settings.DATE_TIME_FORMAT) except Exception as e: logger.error(e) return "" @register.filter(is_safe=True) @stringfilter def custom_markdown(content): from DjangoBlog.utils import CommonMarkdown return mark_safe(CommonMarkdown.get_markdown(content))
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,717
mrpal39/ev_code
refs/heads/master
/scrap/tuto/tuto/spiders/dataviaHTTPPOST.py
import scrapy class DemoSpider(scrapy.Spider): name = 'demo' start_urls = ['http://www.something.com/users/login.php'] def parse(self, response): return scrapy.FormRequest.from_response( response, formdata = {'username': 'admin', 'password': 'confidential'}, callback = self.after_login ) def after_login(self, response): if "authentication failed" in response.body: self.logger.error("Login failed") return # You can continue scraping here
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,718
mrpal39/ev_code
refs/heads/master
/myapi/fullfeblog/webdev/urls.py
from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static from django.contrib.sitemaps.views import sitemap from blog.sitemaps import PostSitemap from django.conf.urls import url, include # from .. import core sitemaps={ 'posts':PostSitemap, } urlpatterns = [ path('admin/', admin.site.urls, ), path('',include('blog.urls')), path('core/',include('core.urls')), path('api/',include('api.urls')), # path('oauth/',include('oauth.urls')), path('accounts/', include('allauth.urls')), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,719
mrpal39/ev_code
refs/heads/master
/tc_zufang/tc_zufang-slave/tc_zufang/utils/GetProxyIp.py
# -*- coding: utf-8 -*- import random import requests def GetIps(): li=[] global count url ='http://139.199.182.250:8000/?types=0&count=300' ips=requests.get(url) for ip in eval(ips.content): li.append(ip[0]+':'+ip[1]) return li GetIps()
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,720
mrpal39/ev_code
refs/heads/master
/awssam/wikidj/wikidj/codehilite.py
from .settings import * from .dev import * # Test codehilite with pygments WIKI_MARKDOWN_KWARGS = { "extensions": [ "codehilite", "footnotes", "attr_list", "headerid", "extra", ] }
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,721
mrpal39/ev_code
refs/heads/master
/scrap/tutorial/scrap/spiders/SitemapSpider.py
from datetime import datetime from scrapy.spiders import SitemapSpider class FilteredSitemapSpider(SitemapSpider): name = 'filtered_sitemap_spider' allowed_domains = ['example.com'] sitemap_urls = ['http://example.com/sitemap.xml'] def sitemap_filter(self, entries): for entry in entries: date_time = datetime.strptime(entry['lastmod'], '%Y-%m-%d') if date_time.year >= 2005: yield entry
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,722
mrpal39/ev_code
refs/heads/master
/Web-UI/mysite/urls.py
"""mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from mysite.views import custom_login, custom_register from django.contrib.auth.views import logout import scrapyproject.urls as projecturls urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^accounts/login/$', custom_login, name='login'), url(r'^accounts/register/$', custom_register, name='registration_register'), url(r'^accounts/logout/$', logout, {'next_page': '/project'}, name='logout'), url(r'^project/', include(projecturls)), ]
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,723
mrpal39/ev_code
refs/heads/master
/awssam/fullfeblog/blog/sitemaps.py
from django.contrib.sitemaps import Sitemap from . models import Post class PostSitemap(Sitemap): changefreq='weekly' # You create a custom sitemap by inheriting the Sitemap class of the sitemaps priority = 0.9 # module. The changefreq and priority attributes indicate the change frequency # of your post pages and their relevance in your website (the maximum value is 1 ). def items(self): return Post.published.all() def lastmod(self,obj): return obj.updated
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,724
mrpal39/ev_code
refs/heads/master
/eswork/articles/articles/spiders/pm_spider.py
# -*- coding: utf-8 -*- import re import json import scrapy import copy from articles.items import PmArticlesItem from articles.utils.common import date_convert class PmSpiderSpider(scrapy.Spider): name = 'pm_spider' allowed_domains = ['woshipm.com'] # start_urls = ['http://www.woshipm.com/__api/v1/stream-list/page/1'] base_url = 'http://www.woshipm.com/__api/v1/stream-list/page/{}' def start_requests(self): for i in range(1, 10): url = self.base_url.format(i) yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): item = PmArticlesItem() # print(response.text) data_set = json.loads(response.text) # print(datas.get('payload')) if data_set: for data in data_set.get('payload'): # print(data) item["title"] = data.get("title", '') item["create_date"] = date_convert(data.get("date", '')) item["url"] = data.get("permalink", '') # item["content"] = data.get("snipper", '').replace('\n', '').replace('\r', '') item["view"] = data.get("view", '') item["tag"] = re.search(r'tag">(.*?)<', data.get("category", '')).group(1) item["url_id"] = data.get('id', '') # print(item) yield scrapy.Request(url=item["url"], callback=self.parse_detail, meta=copy.deepcopy({'item': item})) def parse_detail(self, response): item = response.meta['item'] content = response.xpath("//div[@class='grap']//text()").re(r'\S+') item["content"] = ''.join(content) # print(item) yield item
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,725
mrpal39/ev_code
refs/heads/master
/scrap/properties/properties/spiders/basic.py
# -*- coding: utf-8 -*- import scrapy from properties.items import PropertiesItem class BasicSpider(scrapy.Spider): name = 'basic' allowed_domains = ['web'] start_urls = ( # 'http://web:9312/properties/property_000000.html', # 'https://www.coreapi.org/#examples', # 'https://www.freecodecamp.org/news/git-ssh-how-to', 'https://djangopackages.org', ) # start_urls = ['https://django-dynamic-scraper.readthedocs.io/en/latest/getting_started.html',] def parse(self, response): l.add_xpath('title', '//*[@itemprop="name"][1]/text()', MapCompose(unicode.strip, unicode.title)) l.add_xpath('price', './/*[@itemprop="price"][1]/text()', MapCompose(lambda i: i.replace(',', ''), float), re='[,.0-9]+') l.add_xpath('description', '//*[@itemprop="description"]' '[1]/text()', MapCompose(unicode.strip), Join()) l.add_xpath('address', '//*[@itemtype="http://schema.org/Place"][1]/text()', MapCompose(unicode.strip)) l.add_xpath('image_urls', '//*[@itemprop="image"][1]/@src', MapCompose( lambda i: urlparse.urljoin(response.url, i))) # l.add_xpath('title', '//*[@itemprop="name"][1]/text()') # l.add_xpath('price', './/*[@itemprop="price"]' # '[1]/text()', re='[,.0-9]+') # l.add_xpath('description', '//*[@itemprop="description"]' # '[1]/text()') # l.add_xpath('address', '//*[@itemtype=' # '"http://schema.org/Place"][1]/text()') # l.add_xpath('image_urls', '//*[@itemprop="image"][1]/@src') return l.load_item() # item = PropertiesItem() # item['title'] = response.xpath( # '//*[@id="myrotatingnav"]/div/div[1]').extract() # # item['price'] = response.xpath( # # '//*[@itemprop="price"][1]/text()').re('[.0-9]+') # item['description'] = response.xpath( # '//*[@id="myrotatingnav"]/div/div[1]/a[1]').extract() # # item['address'] = response.xpath( # # '//*[@itemtype="http://schema.org/' # # 'Place"][1]/text()').extract() # # item['image_urls'] = response.xpath( # # '//*[@itemprop="image"][1]/@src').extract() # return item # self.log("title: %s" % response.xpath( # '//*[@itemprop="name"][1]/text()').extract()) # self.log("price: %s" % response.xpath( # '//*[@itemprop="price"][1]/text()').re('[.0-9]+')) # self.log("description: %s" % response.xpath( # '//*[@itemprop="description"][1]/text()').extract()) # self.log("address: %s" % response.xpath( # '//*[@itemtype="http://schema.org/' # 'Place"][1]/text()').extract()) # self.log("image_urls: %s" % response.xpath( # '//*[@itemprop="image"][1]/@src').extract())
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,726
mrpal39/ev_code
refs/heads/master
/awssam/fullfeblog/blog/views.py
# from core.models import Item from django.shortcuts import render # from django.views.generic import ListView,DetailView from django.shortcuts import render, get_object_or_404 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .models import Post from django.views.generic import ( ListView, DetailView, # CreateView, # UpdateView, # DeleteView ) from django.core.mail import send_mail from .forms import EmailPostForm from core.models import Comment from .forms import EmailPostForm, CommentForm , SearchForm from taggit.models import Tag from django.db.models import Count from django.contrib.postgres.search import SearchVector #Building a search view veter def post_search(request): form= SearchForm() query=None results=[] if 'query' in request.GET: form=SearchForm(request.GET) if form.is_valid(): query=form.cleaned_data['query'] results=Post.published.annotate( search =SearchVector('title','body'), ).filter(search=query) return render(request,'search.html',{ 'form':form, 'query':query, 'results':results }) def post_share(request, post_id): # Retrieve post by id post = get_object_or_404(Post, id=post_id, status='published') sent = False if request.method == 'POST': # Form was submitted form = EmailPostForm(request.POST) if form.is_valid(): # Form fields passed validation cd = form.cleaned_data # ... send email post_url = request.build_absolute_uri( post.get_absolute_url()) subject = f"{cd['name']} recommends you read "f"{post.title}" message = f"Read {post.title} at {post_url}\n\n" f"{cd['name']}\'s comments: {cd['comments']}" send_mail(subject, message, 'rp9545416@gmail.com',[cd['to']]) sent = True else: form=EmailPostForm() return render(request, 'share.html', {'post': post, 'form': form, 'sent': sent}) class PostDetailView(DetailView): model = Post class PostListView(ListView): queryset=Post.published.all() context_object_name='posts' paginate_by=2 template_name='list.html' def post_list(request , tag_slug=None): object_list=Post.published.all() tag=None if tag_slug: tag=get_object_or_404(Tag,slug=tag_slug) object_list=object_list.filter(tags__in=[tag]) paginator=Paginator(object_list, 2) # 3 posts in each page page=request.GET.get('page') try: posts=paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts=paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts=paginator.page(paginator.num_pages) return render(request, 'list.html', {'posts': posts, 'page': page, 'tag': tag}) def post_detail(request, year, month, day, post): post=get_object_or_404(Post, slug = post, status = 'published', publish__year = year, publish__month = month, publish__day = day) comments=post.comments.filter(active=True) new_comment=None # List of similar posts post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts=similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4] if request.method== 'POST': #comment aas passed comment_form=CommentForm(data=request.POST) if comment_form.is_valid(): #new coment object new_comment=comment_form.save(comment=False) new_comment.post new_comment.save() else: comment_form=CommentForm() return render(request, 'blog/post_detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, 'similar_posts': similar_posts}) def home(request): return render(request, 'base.html') def about(request): return render(request, 'about.html') # def product(request): # return render (request ,'product.html' ) # class ItemdDetailView(DetailView): # model=Item # template_name="product.html" # def checkout(request): # return render (request ,'checkout.html')
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,727
mrpal39/ev_code
refs/heads/master
/scrap/tutorial/scrap/spiders/spider.py
import scrapy class PySpider(scrapy.Spider): name = 'quots' # start_urls = [ def start_requests(self): urls=['https://pypi.org/'] for url in urls: yield scrapy.Request(url=url, callback=self.parse) # return super().start_requests()() def parse(self, response): page=response.url.split("/")[-0] response.xpath('/html/body/main/div[4]/div/text()').get() filename=f'pyp-{page}.html' with open (filename,'wb')as f: f.write(response.body) self.log(f'saved file{filename}') # return super().parse(response)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,728
mrpal39/ev_code
refs/heads/master
/awssam/ideablog/core/views.py
from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) from .models import Post, Products,MyModel,feeds def home(request): context={ 'posts':Post.objects.all() } return render (request,'blog/home.html',context) class PostListView(ListView): model = Post template_name ='blog/home.html' # <app>/<model>_<viewtype>.html context_object_name ='posts' ordering = ['-date_posted'] paginate_by = 5 class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model=Post template_name = 'blog/post_detail.html' class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content','description'] template_name = 'blog/post_form.html' # <app>/<model>_<viewtype>.html def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class PostUpdateView(LoginRequiredMixin,UserPassesTestMixin,UpdateView): model=Post fields=['title','content','description'] template_name='blog/post_form.html' def form_valid(self, form): form.instance.author=self.request.user return super().form_valid(form) def test_func(self): post =self.get_object() if self.request.user==post.author: return True return False class PostDeleteView(LoginRequiredMixin,UserPassesTestMixin,DeleteView): model=Post success_url='/' template_name = 'blog/post_confirm_delete.html' def test_func(self): post =self.get_object() if self.request.user==post.author: return True return False def index(request): fore=Products.objects.all() feed=feeds.objects.all() context={ 'fore':fore, 'feed':feed } return render(request, 'index.html',context) def about(request): return render(request, 'about.html') def product(request): form =productForm(request.POST) if form.is_valid(): form.save() form =productForm() context={ 'form':form } return render(request, 'product.html',context) def contact(request): feed=feeds.objects.all() return render(request, "contact.html",{'feed':feed})
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,729
mrpal39/ev_code
refs/heads/master
/myapi/devfile/gitapi/jp.py
from fpdf import FPDF from PIL import Image import you import os pdf = FPDF () imagelist = [] # Contains the list of all images to be converted to PDF. # --------------- USER INPUT -------------------- # folder = "/home/rudi/Documents/Pictures/1.png" # Folder containing all the images. name = "pdf" # Name of the output PDF file. # ------------- ADD ALL THE IMAGES IN A LIST ------------- # for dirpath , dirnames , filenames in os . walk ( folder ): for filename in [ f for f in filenames if f . endswith ( ".jpg" )]: full_path = os . path . join ( dirpath , filename ) imagelist . append ( full_path ) imagelist . sort () # Sort the images by name. for i in range ( 0 , len ( imagelist )): print ( imagelist [ i ]) # --------------- ROTATE ANY LANDSCAPE MODE IMAGE IF PRESENT ----------------- # for i in range ( 0 , len ( imagelist )): im1 = Image . open ( imagelist [ i ]) # Open the image. width , height = im1 . size # Get the width and height of that image. if width > height : im2 = im1 . transpose ( Image . ROTATE_270 ) # If width > height, rotate the image. os . remove ( imagelist [ i ]) # Delete the previous image. im2 . save ( imagelist [ i ]) # Save the rotated image. # im.save print ( " \n Found " + str ( len ( imagelist )) + " image files. Converting to PDF.... \n " ) # -------------- CONVERT TO PDF ------------ # for image in imagelist : pdf . add_page () pdf . image ( image , 0 , 0 , 210 , 297 ) # 210 and 297 are the dimensions of an A4 size sheet. pdf . output ( folder + name , "F" ) # Save the PDF. print ( "PDF generated successfully!" )
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,730
mrpal39/ev_code
refs/heads/master
/tc_zufang/tc_zufang-slave/tc_zufang/mongodb_pipeline.py
# -*- coding: utf-8 -*- from pymongo import MongoClient from scrapy import log import traceback from scrapy.exceptions import DropItem class SingleMongodbPipeline(object): MONGODB_SERVER = "101.200.46.191" MONGODB_PORT = 27017 MONGODB_DB = "zufang_fs" def __init__(self): #初始化mongodb连接 try: client = MongoClient(self.MONGODB_SERVER, self.MONGODB_PORT) self.db = client[self.MONGODB_DB] except Exception as e: traceback.print_exc() @classmethod def from_crawler(cls, crawler): cls.MONGODB_SERVER = crawler.settings.get('SingleMONGODB_SERVER', '101.200.46.191') cls.MONGODB_PORT = crawler.settings.getint('SingleMONGODB_PORT', 27017) cls.MONGODB_DB = crawler.settings.get('SingleMONGODB_DB', 'zufang_fs') pipe = cls() pipe.crawler = crawler return pipe def process_item(self, item, spider): if item['pub_time'] == 0: raise DropItem("Duplicate item found: %s" % item) if item['method'] == 0: raise DropItem("Duplicate item found: %s" % item) if item['community']==0: raise DropItem("Duplicate item found: %s" % item) if item['money']==0: raise DropItem("Duplicate item found: %s" % item) if item['area'] == 0: raise DropItem("Duplicate item found: %s" % item) if item['city'] == 0: raise DropItem("Duplicate item found: %s" % item) # if item['phone'] == 0: # raise DropItem("Duplicate item found: %s" % item) # if item['img1'] == 0: # raise DropItem("Duplicate item found: %s" % item) # if item['img2'] == 0: # raise DropItem("Duplicate item found: %s" % item) zufang_detail = { 'title': item.get('title'), 'money': item.get('money'), 'method': item.get('method'), 'area': item.get('area', ''), 'community': item.get('community', ''), 'targeturl': item.get('targeturl'), 'pub_time': item.get('pub_time', ''), 'city':item.get('city',''), 'phone':item.get('phone',''), 'img1':item.get('img1',''), 'img2':item.get('img2',''), } result = self.db['zufang_detail'].insert(zufang_detail) print '[success] the '+item['targeturl']+'wrote to MongoDB database' return item
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,731
mrpal39/ev_code
refs/heads/master
/Web-UI/scrapyproject/models.py
from django.db import models from django.contrib.auth.models import User class Project(models.Model): project_name = models.CharField(max_length=50) user = models.ForeignKey(User) link_generator = models.TextField(blank=True) scraper_function = models.TextField(blank=True) settings_scraper = models.TextField(blank=True) settings_link_generator = models.TextField(blank=True) def __str__(self): return "%s by %s" % (self.project_name, self.user.username) class Item(models.Model): item_name = models.CharField(max_length=50) project = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.item_name class Field(models.Model): field_name = models.CharField(max_length=50) item = models.ForeignKey(Item, on_delete=models.CASCADE) def __str__(self): return self.field_name class Pipeline(models.Model): pipeline_name = models.CharField(max_length=50) pipeline_order = models.IntegerField() pipeline_function = models.TextField(blank=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.pipeline_name class LinkgenDeploy(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) success = models.BooleanField(blank=False) date = models.DateTimeField(auto_now_add=True) version = models.IntegerField(blank=False, default=0) class ScrapersDeploy(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) success = models.TextField(blank=True) date = models.DateTimeField(auto_now_add=True) version = models.IntegerField(blank=False, default=0) class Dataset(models.Model): user = models.ForeignKey(User) database = models.CharField(max_length=50)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,732
mrpal39/ev_code
refs/heads/master
/myapi/fullfeblog/blog/search_indexes.py
from haystack import indexes from django . conf import settings from .models import Article ,Category ,Tag class ArticleIndex ( indexes . SearchIndex , indexes . Indexable ): text = indexes . CharField ( document = True , use_template = True ) def get_model ( self ): return Article def index_queryset ( self , using = None ): return self . get_model (). objects . filter ( status = 'p' )
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,733
mrpal39/ev_code
refs/heads/master
/eswork/articles/articles/items.py
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import redis import scrapy import datetime from scrapy.loader.processors import MapCompose from articles.model.es_types import ArticleType from elasticsearch_dsl.connections import connections es = connections.create_connection(ArticleType._doc_type.using) redis_cli = redis.StrictRedis() def gen_suggests(index, info_tuple): # 根据字符串生成搜索建议数组 used_words = set() suggests = [] for text, weight in info_tuple: if text: # 调用es的analyze接口分析字符串 words = es.indices.analyze(index=index, analyzer="ik_max_word", params={'filter': ["lowercase"]}, body=text) anylyzed_words = set([r["token"] for r in words["tokens"] if len(r["token"]) > 1]) new_words = anylyzed_words - used_words else: new_words = set() if new_words: suggests.append({"input": list(new_words), "weight": weight}) return suggests class PmArticlesItem(scrapy.Item): # define the fields for your item here like: title = scrapy.Field() create_date = scrapy.Field() url = scrapy.Field() content = scrapy.Field() view = scrapy.Field() tag = scrapy.Field() url_id = scrapy.Field() def save_to_es(self): article = ArticleType() article.title = self['title'] article.create_date = self["create_date"] article.content = self["content"] article.url = self["url"] article.view = self["view"] article.tag = self["tag"] article.meta.id = self["url_id"] article.suggest = gen_suggests(ArticleType._doc_type.index, ((article.title, 10), (article.tag, 7))) article.save() redis_cli.incr("pm_count") # redis存储爬虫数量 return
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,734
mrpal39/ev_code
refs/heads/master
/eswork/lcvsearch/test.py
# -*- coding: utf-8 -*- import redis redis_cli = redis.StrictRedis() redis_cli.incr("pm_count")
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,735
mrpal39/ev_code
refs/heads/master
/awssam/iam/iam/settings.py
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'f!7k7a9k10)fbx7#@y@u9u@v3%b)f%h6xxnxf71(21z1uj^#+e' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', # 'oauth2_provider', # 'oauth2_provider', 'corsheaders', 'django.contrib.sites.apps.SitesConfig', 'django.contrib.humanize.apps.HumanizeConfig', 'django_nyt.apps.DjangoNytConfig', 'mptt', 'sekizai', 'sorl.thumbnail', 'wiki.apps.WikiConfig', 'wiki.plugins.attachments.apps.AttachmentsConfig', 'wiki.plugins.notifications.apps.NotificationsConfig', 'wiki.plugins.images.apps.ImagesConfig', 'wiki.plugins.macros.apps.MacrosConfig', ] # AUTHENTICATION_BACKENDS = ( # 'oauth2_provider.backends.OAuth2Backend', # # Uncomment following if you want to access the admin # #'django.contrib.auth.backends.ModelBackend' # ) MIDDLEWARE = [ 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'iam.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.request', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', "sekizai.context_processors.sekizai", ], }, }, ] WSGI_APPLICATION = 'iam.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True SITE_ID = 1 # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' AUTH_USER_MODEL='users.User' LOGIN_URL='/admin/login/' CORS_ORIGIN_ALLOW_ALL = True WIKI_ACCOUNT_HANDLING = True WIKI_ACCOUNT_SIGNUP_ALLOWED = True # export ID =vW1RcAl7Mb0d5gyHNQIAcH110lWoOW2BmWJIero8 # export SECRET=DZFpuNjRdt5xUEzxXovAp40bU3lQvoMvF3awEStn61RXWE0Ses4RgzHWKJKTvUCHfRkhcBi3ebsEfSjfEO96vo2Sh6pZlxJ6f7KcUbhvqMMPoVxRwv4vfdWEoWMGPeIO # #
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,736
mrpal39/ev_code
refs/heads/master
/Web-UI/scrapyproject/scrapy_packages/rabbitmq/connection.py
# -*- coding: utf-8 -*- try: import pika except ImportError: raise ImportError("Please install pika before running scrapy-rabbitmq.") RABBITMQ_CONNECTION_TYPE = 'blocking' RABBITMQ_CONNECTION_PARAMETERS = {'host': 'localhost'} def from_settings(settings, spider_name): connection_type = settings.get('RABBITMQ_CONNECTION_TYPE', RABBITMQ_CONNECTION_TYPE) queue_name = "%s:requests" % spider_name connection_host = settings.get('RABBITMQ_HOST') connection_port = settings.get('RABBITMQ_PORT') connection_username = settings.get('RABBITMQ_USERNAME') connection_pass = settings.get('RABBITMQ_PASSWORD') connection_attempts = 5 retry_delay = 3 credentials = pika.PlainCredentials(connection_username, connection_pass) connection = { 'blocking': pika.BlockingConnection, 'libev': pika.LibevConnection, 'select': pika.SelectConnection, 'tornado': pika.TornadoConnection, 'twisted': pika.TwistedConnection }[connection_type](pika.ConnectionParameters(host=connection_host, port=connection_port, virtual_host='/', credentials=credentials, connection_attempts=connection_attempts, retry_delay=retry_delay)) channel = connection.channel() channel.queue_declare(queue=queue_name, durable=True) return channel def close(channel): channel.close()
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,737
mrpal39/ev_code
refs/heads/master
/march19/devfile/api/urls.py
from django.conf.urls import url from . import views urlpatterns = [ url('api/', views.apiurl, name='index'), ]
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,738
mrpal39/ev_code
refs/heads/master
/myapi/devfile/core/api.py
from django.http.response import HttpResponse from requests_oauthlib import OAuth2Session import json import requests_oauthlib from django.HttpResponse import request import requests from django.shortcuts import redirect, session, # payload={'key1':'search?q=','key2':['form','&api_key=306cf1684a42e4be5ec0a1c60362c2ef']} # client_id = '&api_key=306cf1684a42e4be5ec0a1c60362c2ef' client_id = "<your client key>" client_secret = "<your client secret>" authorization_base_url = 'https://github.com/login/oauth/authorize' token_url = 'https://github.com/login/oauth/access_token' @app.route("/login") def login(): github = OAuth2Session(client_id) authorization_url, state = github.authorization_url(authorization_base_url) # State is used to prevent CSRF, keep this for later. session['oauth_state'] = state return redirect(authorization_url) @app.route("/callback") def callback(): github = OAuth2Session(client_id, state=session['oauth_state']) token = github.fetch_token(token_url, client_secret=client_secret, authorization_response=request.url) return json(github.get('https://api.github.com/user').json())
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,739
mrpal39/ev_code
refs/heads/master
/myapi/fullfeblog/blog/templatetags/blog_tags.py
from django import template from ..models import Post from django.utils.safestring import mark_safe import markdown from django.db.models import Count register = template.Library() @register.filter(name='markdown') def markdown_fromat(text): return mark_safe(markdown.markdown(text)) @register.simple_tag def total_posts(): return Post.published.count() @register.inclusion_tag('latest_posts.html') def show_latest_posts(count=3): latest_posts = Post.published.order_by('-publish')[:count] return {'latest_posts': latest_posts} @register.simple_tag # In the preceding template tag, you build a QuerySet using the annotate() function # to aggregate the total number of comments for each post. You use the Count # aggregation function to store the number of comments in the computed field total_ # comments for each Post object. You order the QuerySet by the computed field in # descending order. You also provide an optional count variable to limit the total def get_most_commented_posts(count=2): return Post.published.annotate( total_comments=Count('comments') ).order_by('-total_comments')[:count]
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,740
mrpal39/ev_code
refs/heads/master
/Web-UI/scrapyproject/migrations/0009_auto_20170215_0657.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('scrapyproject', '0008_scrapersdeploy'), ] operations = [ migrations.AddField( model_name='linkgendeploy', name='version', field=models.IntegerField(default=0), ), migrations.AddField( model_name='scrapersdeploy', name='version', field=models.IntegerField(default=0), ), ]
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,741
mrpal39/ev_code
refs/heads/master
/tc_zufang/tc_zufang/tc_zufang/utils/InsertRedis.py
# -*- coding: utf-8 -*- import redis def inserintotc(str,type): try: r = redis.Redis(host='127.0.0.1', port=6379, db=0) except: print '连接redis失败' else: if type == 1: r.lpush('start_urls', str) def inserintota(str,type): try: r = redis.Redis(host='127.0.0.1', port=6379, db=0) except: print '连接redis失败' else: if type == 2: r.lpush('tczufang_tc:requests', str)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,742
mrpal39/ev_code
refs/heads/master
/awssam/myscrapyproject/dev/corescrap/apps.py
from django.apps import AppConfig class CorescrapConfig(AppConfig): name = 'corescrap'
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,743
mrpal39/ev_code
refs/heads/master
/scrap/tuto/tuto/items.py
# -*- 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 from scrapy.item import Item ,Field from scrapy.loader import ItemLoader from scrapy.loader.processors import TakeFirst, MapCompose, Join class DemoLoader(ItemLoader): default_output_processor = TakeFirst() title_in = MapCompose(unicode.title) title_out = Join() size_in = MapCompose(unicode.strip) # you can continue scraping here class DemoItem(scrapy.Item): # define the fields for your item here like: product_title = scrapy.Field() product_link = scrapy.Field() product_description = scrapy.Field() pass
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,744
mrpal39/ev_code
refs/heads/master
/tc_zufang/tc_zufang-slave/tc_zufang/spiders/tczufang_detail_spider.py
# -*- coding: utf-8 -*- from scrapy_redis.spiders import RedisSpider from scrapy.selector import Selector from tc_zufang.utils.result_parse import list_first_item from scrapy.http import Request from tc_zufang.items import TcZufangItem import re defaultencoding = 'utf-8' ''' 58同城的爬虫 ''' #继承自RedisSpider,则start_urls可以从redis读取 #继承自BaseSpider,则start_urls需要写出来 class TczufangSpider(RedisSpider): name='tczufang' redis_key = 'tczufang_tc:requests' #解析从start_urls下载返回的页面 #页面页面有两个目的: #第一个:解析获取下一页的地址,将下一页的地址传递给爬虫调度器,以便作为爬虫的下一次请求 #第二个:获取详情页地址,再对详情页进行下一步的解析 #对详情页进行下一步的解析 def parse(self, response): tczufangItem=TcZufangItem() response_url = re.findall('^http\:\/\/\w+\.58\.com', response.url) response_selector = Selector(response) # 字段的提取可以使用在终端上scrapy shell进行调试使用 # 帖子名称 raw_title=list_first_item(response_selector.xpath(u'//div[contains(@class,"house-title")]/h1[contains(@class,"c_333 f20")]/text()').extract()) if raw_title: tczufangItem['title'] =raw_title.encode('utf8') #t帖子发布时间,进一步处理 raw_time=list_first_item(response_selector.xpath(u'//div[contains(@class,"house-title")]/p[contains(@class,"house-update-info c_888 f12")]/text()').extract()) try: tczufangItem['pub_time'] =re.findall(r'\d+\-\d+\-\d+\s+\d+\:\d+\:\d+',raw_time)[0] except: tczufangItem['pub_time']=0 #租金 tczufangItem['money']=list_first_item(response_selector.xpath(u'//div[contains(@class,"house-pay-way f16")]/span[contains(@class,"c_ff552e")]/b[contains(@class,"f36")]/text()').extract()) # 租赁方式 raw_method=list_first_item(response_selector.xpath(u'//ul[contains(@class,"f14")]/li[1]/span[2]/text()').extract()) try: tczufangItem['method'] =raw_method.encode('utf8') except: tczufangItem['method']=0 # 所在区域 try: area=response_selector.xpath(u'//ul[contains(@class,"f14")]/li/span/a[contains(@class,"c_333")]/text()').extract()[1] except: area='' if area: area=area try: area2=response_selector.xpath(u'//ul[contains(@class,"f14")]/li/span/a[contains(@class,"c_333")]/text()').extract()[2] except: area2='' raw_area=area+"-"+area2 if raw_area: raw_area=raw_area.encode('utf8') tczufangItem['area'] =raw_area if raw_area else None # 所在小区 try: raw_community = response_selector.xpath(u'//ul[contains(@class,"f14")]/li/span/a[contains(@class,"c_333")]/text()').extract()[0] if raw_community: raw_community=raw_community.encode('utf8') tczufangItem['community']=raw_community if raw_community else None except: tczufangItem['community']=0 # 帖子详情url tczufangItem['targeturl']=response.url #帖子所在城市 tczufangItem['city']=response.url.split("//")[1].split('.')[0] #帖子的联系电话 try: tczufangItem['phone']=response_selector.xpath(u'//div[contains(@class,"house-fraud-tip")]/span[1]/em[contains(@class,"phone-num")]/text()').extract()[0] except: tczufangItem['phone']=0 # 图片1的联系电话 try: tczufangItem['img1'] = response_selector.xpath(u'//ul[contains(@class,"pic-list-wrap pa")]/li[1]/@data-src').extract()[0] except: tczufangItem['img1'] = 0 # 图片1的联系电话 try: tczufangItem['img2'] = response_selector.xpath(u'//ul[contains(@class,"pic-list-wrap pa")]/li[2]/@data-src').extract()[0] except: tczufangItem['img2'] = 0 yield tczufangItem
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,745
mrpal39/ev_code
refs/heads/master
/cte/properties/properties/items.py
# Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.item import Item,Field class PropertiesItem(): title=Field() price=Field() description=Field() address = Field() image_urls = Field() #imagescalculaitons images = Field() locations = Field() #housekeeping url=Field() project = Field() spider=Field() server = Field() date=Field()
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,746
mrpal39/ev_code
refs/heads/master
/myapi/fullfeblog/blog/views.py
# from core.models import Item from django.shortcuts import render # from django.views.generic import ListView,DetailView from django.shortcuts import render, get_object_or_404 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .models import Post from django.views.generic import ( ListView, DetailView, # CreateView, # UpdateView, # DeleteView ) from django.core.mail import send_mail from .forms import EmailPostForm from core.models import Comment from .forms import EmailPostForm, CommentForm , SearchForm from taggit.models import Tag from django.db.models import Count from django.contrib.postgres.search import SearchVector #Building a search view veter import requests def post_api(request): form= SearchForm() query=None results=[] api_key='306cf1684a42e4be5ec0a1c60362c2ef' url=("https://libraries.io/api/search?q={}&api_key={}".format(form,api_key)) response = requests.get(url) response_dict = response.json() # if 'query' in request.GET: # response_dict=SearchForm(request.GET) # if response_dict.is_valid(): # query=form.cleaned_data['query'] # results=Post.published.annotate( # search =SearchVector('title','body'), # ).filter(search=query) return render(request,'search.html',{ 'form':response_dict, # 'query':query, # 'results':results }) def post_search(request): form= SearchForm() query=None results=[] if 'query' in request.GET: form=SearchForm(request.GET) if form.is_valid(): query=form.cleaned_data['query'] results=Post.published.annotate( search =SearchVector('title','body'), ).filter(search=query) return render(request,'api.html',{ 'form':form, 'query':query, 'results':results }) def post_share(request, post_id): # Retrieve post by id post = get_object_or_404(Post, id=post_id, status='published') sent = False if request.method == 'POST': # Form was submitted form = EmailPostForm(request.POST) if form.is_valid(): # Form fields passed validation cd = form.cleaned_data # ... send email post_url = request.build_absolute_uri( post.get_absolute_url()) subject = f"{cd['name']} recommends you read "f"{post.title}" message = f"Read {post.title} at {post_url}\n\n" f"{cd['name']}\'s comments: {cd['comments']}" send_mail(subject, message, 'rp9545416@gmail.com',[cd['to']]) sent = True else: form=EmailPostForm() return render(request, 'share.html', {'post': post, 'form': form, 'sent': sent}) class PostDetailView(DetailView): model = Post pk_url_kwarg = 'article_id' context_object_name = "article" def get_object(self, queryset=None): obj = super(PostDetailView, self).get_object() obj.viewed() self.object = obj return obj def get_context_data(self, **kwargs): articleid = int(self.kwargs[self.pk_url_kwarg]) comment_form = CommentForm() user = self.request.user # 如果用户已经登录,则隐藏邮件和用户名输入框 if user.is_authenticated and not user.is_anonymous and user.email and user.username: comment_form.fields.update({ 'email': forms.CharField(widget=forms.HiddenInput()), 'name': forms.CharField(widget=forms.HiddenInput()), }) comment_form.fields["email"].initial = user.email comment_form.fields["name"].initial = user.username article_comments = self.object.comment_list() kwargs['form'] = comment_form kwargs['article_comments'] = article_comments kwargs['comment_count'] = len( article_comments) if article_comments else 0 kwargs['next_article'] = self.object.next_article kwargs['prev_article'] = self.object.prev_article return super(ArticleDetailView, self).get_context_data(**kwargs) class PostListView(ListView): queryset=Post.published.all() context_object_name='posts' paginate_by=2 template_name='list.html' page_type = '' page_kwarg = 'page' def get_view_cache_key(self): return self.request.get['pages'] @property def page_number(self): page_kwarg = self.page_kwarg page = self.kwargs.get( page_kwarg) or self.request.GET.get(page_kwarg) or 1 return page def get_queryset_cache_key(self): raise NotImplementedError() def get_queryset_data(self): """ 子类重写.获取queryset的数据 """ raise NotImplementedError() # def get_queryset_from_cache(self, cache_key): # value = cache.get(cache_key) # if value: # logger.info('get view cache.key:{key}'.format(key=cache_key)) # return value # else: # article_list = self.get_queryset_data() # cache.set(cache_key, article_list) # logger.info('set view cache.key:{key}'.format(key=cache_key)) # return article_list # def get_queryset(self): # key = self.get_queryset_cache_key() # value = self.get_queryset_from_cache(key) # return value # def get_context_data(self, **kwargs): # kwargs['linktype'] = self.link_type # return super(PostListView, self).get_context_data(**kwargs) def post_list(request , tag_slug=None): object_list=Post.published.all() tag=None if tag_slug: tag=get_object_or_404(Tag,slug=tag_slug) object_list=object_list.filter(tags__in=[tag]) paginator=Paginator(object_list, 2) # 3 posts in each page page=request.GET.get('page') try: posts=paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts=paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts=paginator.page(paginator.num_pages) return render(request, 'list.html', {'posts': posts, 'page': page, 'tag': tag}) def post_detail(request, year, month, day, post): post=get_object_or_404(Post, slug = post, status = 'published', publish__year = year, publish__month = month, publish__day = day) comments=post.comments.filter(active=True) new_comment=None # List of similar posts post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts=similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4] if request.method== 'POST': #comment aas passed comment_form=CommentForm(data=request.POST) if comment_form.is_valid(): #new coment object new_comment=comment_form.save(comment=False) new_comment.post new_comment.save() else: comment_form=CommentForm() return render(request, 'blog/post_detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, 'similar_posts': similar_posts}) def home(request): return render(request, 'base.html') def about(request): return render(request, 'about.html') # def product(request): # return render (request ,'product.html' ) # class ItemdDetailView(DetailView): # model=Item # template_name="product.html" # def checkout(request): # return render (request ,'checkout.html')
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,747
mrpal39/ev_code
refs/heads/master
/scrap/first_scrapy/first_scrapy/items.py
import scrapy class FirstScrapyItem(scrapy.Item): # define the fields for your item here like: item=DmozItem() item ['title'] = scrapy.Field() item ['url'] = scrapy.Field() item ['desc'] = scrapy.Field()
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,748
mrpal39/ev_code
refs/heads/master
/eswork/articles/articles/utils/common.py
import hashlib import datetime def date_convert(value): # 日期转化 try: create_date = datetime.datetime.strptime(value, "%Y/%m/%d").date() except Exception as e: print(e) create_date = datetime.datetime.now().date() return create_date def get_md5(url): # url md5加密 if isinstance(url, str): url = url.encode("utf-8") m = hashlib.md5() m.update(url) return m.hexdigest() if __name__ == '__main__': print(date_convert('2020/02/28')) print(get_md5('http://www.woshipm.com/it/3443027.html'))
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,749
mrpal39/ev_code
refs/heads/master
/tc_zufang/django_web/django_web/test.py
# -*- coding: utf-8 -*- res=u'\u4e30\u6cf0\u57ce' # rr=res.encode('gbk') print res
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,750
mrpal39/ev_code
refs/heads/master
/march19/devfile/api/views.py
from django.shortcuts import render from urllib.request import urlopen from django.shortcuts import render from django.views import View import requests # class apiurl(View): def apiurl(request): url =requests('https://api.github.com/') data=url.requests.json() context ={ 'data':data } return render(request,'index.html', context)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,751
mrpal39/ev_code
refs/heads/master
/tc_zufang/tc_zufang-slave/tc_zufang/utils/message.py
# -*- coding: utf-8 -*- import smtplib from email.mime.text import MIMEText from email.header import Header def sendMessage_warning(): server = smtplib.SMTP('smtp.163.com', 25) server.login('seven_2016@163.com', 'ssy102009') msg = MIMEText('爬虫slave被封警告!请求解封!', 'plain', 'utf-8') msg['From'] = 'seven_2016@163.com <seven_2016@163.com>' msg['Subject'] = Header(u'爬虫被封禁警告!', 'utf8').encode() msg['To'] = u'seven <751401459@qq.com>' server.sendmail('seven_2016@163.com', ['751401459@qq.com'], msg.as_string())
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,752
mrpal39/ev_code
refs/heads/master
/cte/projectfile/projectfile/items.py
# Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy from scrapy import Item, Field # define the fields for your item here like: # class SainsburysItem(scrapy.Item): name = scrapy.Field() class SainsburysItem(Item): url = Field() product_name = Field() product_image = Field() price_per_unit = Field() unit = Field() rating = Field() product_reviews = Field() item_code = Field() nutritions = Field() product_origin = Field() class FlatSainsburysItem(Item): url = Field() product_name = Field() product_image = Field() price_per_unit = Field() unit = Field() rating = Field() product_reviews = Field() item_code = Field() product_origin = Field() energy = Field() energy_kj = Field() kcal = Field() fibre_g = Field() carbohydrates_g = Field() of_which_sugars = Field()
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,753
mrpal39/ev_code
refs/heads/master
/awssam/wikidj/wikidj/dev.py
from . settings import * DEBUG = True for template_engine in TEMPLATES: template_engine["OPTIONS"]["debug"] = True EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" try: import debug_toolbar # @UnusedImport MIDDLEWARE = list(MIDDLEWARE) + [ "debug_toolbar.middleware.DebugToolbarMiddleware", ] INSTALLED_APPS = list(INSTALLED_APPS) + ["debug_toolbar"] INTERNAL_IPS = ("127.0.0.1",) DEBUG_TOOLBAR_CONFIG = {"INTERCEPT_REDIRECTS": False} except ImportError: pass
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,754
mrpal39/ev_code
refs/heads/master
/scrap/tutorial/scrap/spiders/reactor.py
import logging import scrapy logger = logging.getLogger('mycustomlogger') class MySpider(scrapy.Spider): name = 'myspider1' start_urls = ['https://scrapinghub.com'] def parse(self, response): logger.info('Parse function called on %s', response.url)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,755
mrpal39/ev_code
refs/heads/master
/scrap/example_project/open_news/migrations/0002_document.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-02-24 08:54 from __future__ import unicode_literals from django.db import migrations, models import open_news.models class Migration(migrations.Migration): dependencies = [ ('open_news', '0001_initial'), ] operations = [ migrations.CreateModel( name='Document', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('file', models.FileField(upload_to=open_news.models.upload_location)), ], ), ]
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,756
mrpal39/ev_code
refs/heads/master
/tc_zufang/django_web/datashow/views.py
# -*- coding: utf-8 -*- from django.shortcuts import render from . models import ItemInfo from django.core.paginator import Paginator from mongoengine import connect connect("zufang_fs",host='127.0.0.1') # Create your views here. def document(request): limit=15 zufang_info=ItemInfo.objects pageinator=Paginator(zufang_info,limit) page=request.GET.get('page',1) loaded = pageinator.page(page) cities=zufang_info.distinct("city") citycount=len(cities) context={ 'itemInfo':loaded, 'counts':zufang_info.count, 'cities':cities, 'citycount':citycount } return render(request,'document.html',context) def binzhuantu(): ##饼状图 citys = [] zufang_info = ItemInfo.objects sums = float(zufang_info.count()) cities = zufang_info.distinct("city") for city in cities: length = float(len(zufang_info(city=city))) ocu = round(float(length / sums * 100)) item = [city.encode('raw_unicode_escape'), ocu] citys.append(item) return citys def chart(request): ##饼状图 citys=binzhuantu() # #柱状图 # zufang_info = ItemInfo.objects # res = zufang_info.all() # cities = zufang_info.distinct("city") # cc = [] # time = [] # counts = [] # for re in res: # if re.pub_time != None: # if re.pub_time > '2017-03-01': # if re.pub_time < '2017-04-01': # time.append(re.city) # for city in cities: # count = time.count(city) # counts.append(count) # item = city.encode('utf8') # cc.append(item) context ={ # 'count': counts, # 'citys': cc, 'cities':citys, } return render(request,'chart.html',context) def cloud(request): zufang_info = ItemInfo.objects res = zufang_info.distinct('community') length=len(res) context={ 'count':length, 'wenzi':res } return render(request, 'test.html',context) def test(request): zufang_info = ItemInfo.objects rr=[] res = zufang_info.distinct('community') i=0 while i<500: item=res[i] rr.append(item) i=i+1 length = len(res) context = { 'count': length, 'wenzi': rr } return render(request,'test.html',context)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,757
mrpal39/ev_code
refs/heads/master
/awssam/django-blog/src/blog/context_processors.py
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: context_processors.py Description : Author : JHao date: 2017/4/14 ------------------------------------------------- Change Activity: 2017/4/14: ------------------------------------------------- """ __author__ = 'JHao' import importlib from django_blog import blogroll from blog.models import Category, Article, Tag, Comment def sidebar(request): category_list = Category.objects.all() # 所有类型 blog_top = Article.objects.all().values("id", "title", "view").order_by('-view')[0:6] # 文章排行 tag_list = Tag.objects.all() # 标签 comment = Comment.objects.all().order_by('-create_time')[0:6] # 评论 importlib.reload(blogroll) # 友链 return { 'category_list': category_list, 'blog_top': blog_top, 'tag_list': tag_list, 'comment_list': comment, 'blogroll': blogroll.sites } if __name__ == '__main__': pass
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,758
mrpal39/ev_code
refs/heads/master
/myapi/devfile/request/api1.py
import requests import json url='https://www.scraping-bot.io/rawHtmlPage.html' username = 'yourUsername' apiKey = 'yourApiKey' apiUrl = "http://api.scraping-bot.io/scrape/raw-html" payload = json.dumps({"url":url}) headers = { 'Content-Type': "application/json" } response = requests.request("POST", apiUrl, data=payload, auth=(username,apiKey), headers=headers) print(response.text) import requests import json url='https://www.scraping-bot.io/rawHtmlPage.html' username = 'yourUsername' apiKey = 'yourApiKey' apiEndPoint = "http://api.scraping-bot.io/scrape/raw-html" options = { "useChrome": False,#set to True if you want to use headless chrome for javascript rendering "premiumProxy": False, # set to True if you want to use premium proxies Unblock Amazon,Google,Rakuten "proxyCountry": None, # allows you to choose a country proxy (example: proxyCountry:"FR") "waitForNetworkRequests":False # wait for most ajax requests to finish until returning the Html content (this option can only be used if useChrome is set to true), # this can slowdown or fail your scraping if some requests are never ending only use if really needed to get some price loaded asynchronously for example } payload = json.dumps({"url":url,"options":options}) headers = { 'Content-Type': "application/json" } response = requests.request("POST", apiEndPoint, data=payload, auth=(username,apiKey), headers=headers) print(response.text) https://libraries.io/api/NPM/base62?api_key=306cf1684a42e4be5ec0a1c60362c2ef import requests import json url='https://www.scraping-bot.io/example-ebay.html' username = 'yourUsername' apiKey = '306cf1684a42e4be5ec0a1c60362c2ef' apiEndPoint = "http://api.scraping-bot.io/scrape/retail" payload = json.dumps({"url":url,"options":options}) headers = { 'Content-Type': "application/json" } response = requests.request("POST", apiEndPoint, data=payload, auth=(username,apiKey), headers=headers) print(response.text)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,759
mrpal39/ev_code
refs/heads/master
/awssam/ideablog/core/forms.py
from django import forms from .models import Products class productForm(forms.ModelForm): class Meta: model=Products fields=['title','description','price']
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,760
mrpal39/ev_code
refs/heads/master
/scrap/tutorial/scrap/spiders/login.py
import scrapy def authentication_failed(response): pass class LoginSpider(scrapy.Spider): name='ex' start_urls=['https://www.facebook.com/login.php'] def parse(self,response): return scrapy.FormRequest.from_response( response,formdata={'username':'john','password':'secret'}, callback=self.after_login ) def after_login(self,response): if authentication_failed(response): self.logger.error('Login Failed') return page = response.url.split("/")[-2] filename = f'quotes-{page}.html' with open(filename, 'wb') as f: f.write(response.body)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,761
mrpal39/ev_code
refs/heads/master
/Web-UI/scrapyproject/scrapy_packages/sample_settings.py
#rabbitmq and mongodb settings SCHEDULER = ".rabbitmq.scheduler.Scheduler" SCHEDULER_PERSIST = True RABBITMQ_HOST = 'ip address' RABBITMQ_PORT = 5672 RABBITMQ_USERNAME = 'guest' RABBITMQ_PASSWORD = 'guest' MONGODB_PUBLIC_ADDRESS = 'ip:port' # This will be shown on the web interface, but won't be used for connecting to DB MONGODB_URI = 'ip:port' # Actual uri to connect to DB MONGODB_USER = '' MONGODB_PASSWORD = '' MONGODB_SHARDED = False MONGODB_BUFFER_DATA = 100 LINK_GENERATOR = 'http://192.168.0.209:6800' # Set your link generator worker address here SCRAPERS = ['http://192.168.0.210:6800', 'http://192.168.0.211:6800', 'http://192.168.0.212:6800'] # Set your scraper worker addresses here LINUX_USER_CREATION_ENABLED = False # Set this to True if you want a linux user account created during registration
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,762
mrpal39/ev_code
refs/heads/master
/Web-UI/scrapyproject/urls.py
from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$', views.main_page, name="mainpage"), url(r'^create/$', views.create_new, name="newproject"), url(r'^manage/(?P<projectname>[\w]+)/', views.manage_project, name="manageproject"), url(r'^delete/(?P<projectname>[\w]+)/', views.delete_project, name="deleteproject"), url(r'^createitem/(?P<projectname>[\w]+)/', views.create_item, name="newitem"), url(r'^edititems/(?P<projectname>[\w]+)/', views.itemslist, name="listitems"), url(r'^deleteitem/(?P<projectname>[\w]+)/(?P<itemname>[\w]+)/', views.deleteitem, name="deleteitem"), url(r'^edititem/(?P<projectname>[\w]+)/(?P<itemname>[\w]+)/', views.edititem, name="edititem"), url(r'^addpipeline/(?P<projectname>[\w]+)/', views.addpipeline, name="addpipeline"), url(r'^editpipelines/(?P<projectname>[\w]+)/', views.pipelinelist, name="listpipelines"), url(r'^editpipeline/(?P<projectname>[\w]+)/(?P<pipelinename>[\w]+)/', views.editpipeline, name="editpipeline"), url(r'^deletepipeline/(?P<projectname>[\w]+)/(?P<pipelinename>[\w]+)/', views.deletepipeline, name="deletepipeline"), url(r'^linkgenerator/(?P<projectname>[\w]+)/', views.linkgenerator, name="linkgenerator"), url(r'^scraper/(?P<projectname>[\w]+)/', views.scraper, name="scraper"), url(r'^deploy/(?P<projectname>[\w]+)/', views.deploy, name='deploy'), url(r'^changepassword/$', views.change_password, name="changepass"), url(r'^deploystatus/(?P<projectname>[\w]+)/', views.deployment_status, name="deploystatus"), url(r'^startproject/(?P<projectname>[\w]+)/(?P<worker>[\w]+)/', views.start_project, name="startproject"), url(r'^stopproject/(?P<projectname>[\w]+)/(?P<worker>[\w]+)/', views.stop_project, name="stopproject"), url(r'^allworkerstatus/(?P<projectname>[\w]+)/', views.get_project_status_from_all_workers, name="allworkerstatus"), url(r'^getlog/(?P<projectname>[\w]+)/(?P<worker>[\w]+)/', views.see_log_file, name="seelogfile"), url(r'^allprojectstatus/', views.gather_status_for_all_projects, name="allprojectstatus"), url(r'^editsettings/(?P<settingtype>[\w]+)/(?P<projectname>[\w]+)/', views.editsettings, name="editsettings"), url(r'^startonall/(?P<projectname>[\w]+)/', views.start_project_on_all, name="startonall"), url(r'^stoponall/(?P<projectname>[\w]+)/', views.stop_project_on_all, name="stoponall"), url(r'^globalstatus/', views.get_global_system_status, name="globalstatus"), url(r'^sharedb/(?P<projectname>[\w]+)/', views.share_db, name="sharedatabase"), url(r'^shareproject/(?P<projectname>[\w]+)/', views.share_project, name="shareproject"), url(r'^dbpreview/(?P<db>[\w]+)/', views.database_preview, name="dbpreview"), ]
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,763
mrpal39/ev_code
refs/heads/master
/awssam/ideablog/core/migrations/0003_auto_20201113_0620.py
# Generated by Django 3.1.3 on 2020-11-13 06:20 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0002_products'), ] operations = [ migrations.RenameModel( old_name='Post', new_name='feeds', ), ]
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,764
mrpal39/ev_code
refs/heads/master
/cte/properties/properties/spiders/webi.py
import scrapy class WebiSpider(scrapy.Spider): name = 'webi' allowed_domains = ['web'] start_urls = ['http://web/'] def parse(self, response): pass
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,765
mrpal39/ev_code
refs/heads/master
/scrap/tuto/tuto/spiders/scrapy.py
import scrapy from scrapy.spiders import CSVFeedSpider from scrapy.spiders import SitemapSpider from scrapy.spiders import CrawlSpider,Rule from scrapy.linkextractor import LinkExtractor from tuto.items import DemoItem from scrapy.loader import ItemLoader from tuto.items import Demo class DemoSpider(CrawlSpider): name='demo' allowed_domais=["www.tutorialspoint.com"] start_url=["https://www.tutorialspoint.com/scrapy/index.htm"] def parse(self, response): l = ItemLoader(item = Product(), response = response) l.add_xpath("title", "//div[@class = 'product_title']") l.add_xpath("title", "//div[@class = 'product_name']") l.add_xpath("desc", "//div[@class = 'desc']") l.add_css("size", "div#size]") l.add_value("last_updated", "yesterday") return l.load_item() # loader = ItemLoader(item = Item()) # loader.add_xpath('social''a[@class = "social"]/@href') # loader.add_xpath('email','a[@class = "email"]/@href') # rules =( # Rule(LinkExtractor(allow=(),restrict_xpaths=(''))) # ) class DemoSpider(CSVFeedSpider): name = "demo" allowed_domains = ["www.demoexample.com"] start_urls = ["http://www.demoexample.com/feed.csv"] delimiter = ";" quotechar = "'" headers = ["product_title", "product_link", "product_description"] def parse_row(self, response, row): self.logger.info("This is row: %r", row) item = DemoItem() item["product_title"] = row["product_title"] item["product_link"] = row["product_link"] item["product_description"] = row["product_description"] return item class DemoSpider(SitemapSpider): urls = ["http://www.demoexample.com/sitemap.xml"] rules = [ ("/item/", "parse_item"), ("/group/", "parse_group"), ] def parse_item(self, response): # you can scrap item here def parse_group(self, response): # you can scrap group here
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,766
mrpal39/ev_code
refs/heads/master
/awssam/iam/users/views.py
from oauth2_provider.views.generic import ProtectedResourceView from django.http import HttpResponse
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,767
mrpal39/ev_code
refs/heads/master
/awssam/django-blog/src/blog/templatetags/custom_filter.py
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: custom_filter.py Description : Author : JHao date: 2017/4/14 ------------------------------------------------- Change Activity: 2017/4/14: ------------------------------------------------- """ __author__ = 'JHao' import markdown from django import template from django.utils.safestring import mark_safe from django.template.defaultfilters import stringfilter register = template.Library() @register.filter def slice_list(value, index): return value[index] @register.filter(is_safe=True) @stringfilter def custom_markdown(value): content = mark_safe(markdown.markdown(value, output_format='html5', extensions=[ 'markdown.extensions.extra', 'markdown.extensions.fenced_code', 'markdown.extensions.tables', ], safe_mode=True, enable_attributes=False)) return content @register.filter def tag2string(value): """ 将Tag转换成string >'python,爬虫' :param value: :return: """ return ','.join([each.get('tag_name', '') for each in value]) if __name__ == '__main__': pass
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,768
mrpal39/ev_code
refs/heads/master
/eswork/lcvsearch/search/models.py
from django.db import models # Create your models here. from datetime import datetime from elasticsearch_dsl import DocType, Date, Nested, Boolean, \ analyzer, InnerObjectWrapper, Completion, Keyword, Text, Integer from elasticsearch_dsl.analysis import CustomAnalyzer as _CustomAnalyzer from elasticsearch_dsl.connections import connections connections.create_connection(hosts=["localhost"]) class CustomAnalyzer(_CustomAnalyzer): def get_analysis_definition(self): return {} ik_analyzer = CustomAnalyzer("ik_max_word", filter=["lowercase"]) class ArticleType(DocType): """ # elasticsearch_dsl安装5.4版本 """ # 文章类型 suggest = Completion(analyzer=ik_analyzer) title = Text(analyzer="ik_max_word") create_date = Date() url = Keyword() view = Integer() category = Text(analyzer="ik_max_word") content = Text(analyzer="ik_max_word") class Meta: index = "pm" doc_type = "article" if __name__ == "__main__": data = ArticleType.init() print(data)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,769
mrpal39/ev_code
refs/heads/master
/Web-UI/scrapyproject/admin.py
from django.contrib import admin from .models import Project, Item, Field, Pipeline # Register your models here. admin.site.register(Project) admin.site.register(Item) admin.site.register(Field) admin.site.register(Pipeline)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,770
mrpal39/ev_code
refs/heads/master
/awssam/django-blog/src/blog/models.py
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: models.py Description : Author : JHao date: 2016/11/18 ------------------------------------------------- Change Activity: 2016/11/18: ------------------------------------------------- """ from django.db import models from django.conf import settings # Create your models here. class Tag(models.Model): tag_name = models.CharField('标签名称', max_length=30) def __str__(self): return self.tag_name class Article(models.Model): title = models.CharField(max_length=200) # 博客标题 category = models.ForeignKey('Category', verbose_name='文章类型', on_delete=models.CASCADE) date_time = models.DateField(auto_now_add=True) # 博客日期 content = models.TextField(blank=True, null=True) # 文章正文 digest = models.TextField(blank=True, null=True) # 文章摘要 author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='作者', on_delete=models.CASCADE) view = models.BigIntegerField(default=0) # 阅读数 comment = models.BigIntegerField(default=0) # 评论数 picture = models.CharField(max_length=200) # 标题图片地址 tag = models.ManyToManyField(Tag) # 标签 def __str__(self): return self.title def sourceUrl(self): source_url = settings.HOST + '/blog/detail/{id}'.format(id=self.pk) return source_url # 给网易云跟帖使用 def viewed(self): """ 增加阅读数 :return: """ self.view += 1 self.save(update_fields=['view']) def commenced(self): """ 增加评论数 :return: """ self.comment += 1 self.save(update_fields=['comment']) class Meta: # 按时间降序 ordering = ['-date_time'] class Category(models.Model): name = models.CharField('文章类型', max_length=30) created_time = models.DateTimeField('创建时间', auto_now_add=True) last_mod_time = models.DateTimeField('修改时间', auto_now=True) class Meta: ordering = ['name'] verbose_name = "文章类型" verbose_name_plural = verbose_name def __str__(self): return self.name class Comment(models.Model): title = models.CharField("标题", max_length=100) source_id = models.CharField('文章id或source名称', max_length=25) create_time = models.DateTimeField('评论时间', auto_now=True) user_name = models.CharField('评论用户', max_length=25) url = models.CharField('链接', max_length=100) comment = models.CharField('评论内容', max_length=500)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,771
mrpal39/ev_code
refs/heads/master
/scrap/tuto/tuto/spiders/callable.py
from types import resolve_bases import scrapy from scrapy.spidermiddlewares.httperror import HttpError from twisted.internet.error import DNSLookupError from twisted.internet.error import TimeoutError,TCPTimedOutError class DemoSpider(scrapy.Spider): name='demo' start_urls=[ "http://www.httpbin.org/", # HTTP 200 expected "http://www.httpbin.org/status/404", # Webpage not found "http://www.httpbin.org/status/500", # Internal server error "http://www.httpbin.org:12345/", # timeout expected "http://www.httphttpbinbin.org/", ] def start_requests(self): for u in self.start_urls: yield scrapy.Request(u,callback=self.parse_httpbin), dont_filter=True def parse_httpbin(self, response): self.logger.info('Recieved response from {}'.format(response.url)) # ... def errback_httpbin(self,failure): self.logger.error(repr(failure)) if failure.check(HttpError): response=failure.value.response self.logger.error('htttp Error occireed on %s',response.url) elif failure.check(DNSLookupError) : response=failure.request self.logger.error("DNSLookupError occurred on %s", request.url) elif failure.check(TimeoutError,TCPTimedOutError): request =failure.request self.logger.eerror("timeout occured on %s",request.url)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,772
mrpal39/ev_code
refs/heads/master
/scrap/example_project/open_news/models.py
#Stage 2 Update (Python 3) from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible from django.db import models from django.db.models.signals import pre_delete from django.dispatch import receiver from scrapy_djangoitem import DjangoItem from dynamic_scraper.models import Scraper, SchedulerRuntime @python_2_unicode_compatible class NewsWebsite(models.Model): name = models.CharField(max_length=200) url = models.URLField() scraper = models.ForeignKey(Scraper, blank=True, null=True, on_delete=models.SET_NULL) scraper_runtime = models.ForeignKey(SchedulerRuntime, blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return self.name @python_2_unicode_compatible class Article(models.Model): title = models.CharField(max_length=200) news_website = models.ForeignKey(NewsWebsite) description = models.TextField(blank=True) url = models.URLField(blank=True) thumbnail = models.CharField(max_length=200, blank=True) checker_runtime = models.ForeignKey(SchedulerRuntime, blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return self.title class ArticleItem(DjangoItem): django_model = Article @receiver(pre_delete) def pre_delete_handler(sender, instance, using, **kwargs): if isinstance(instance, NewsWebsite): if instance.scraper_runtime: instance.scraper_runtime.delete() if isinstance(instance, Article): if instance.checker_runtime: instance.checker_runtime.delete() pre_delete.connect(pre_delete_handler) def upload_location(instance, filename): return '%s/documents/%s' % (instance.user.username, filename) class Document(models.Model): # user = models.ForeignKey(settings.AUTH_USER_MODEL) # category = models.ForeignKey(Category, on_delete=models.CASCADE) file = models.FileField(upload_to=upload_location) def __str__(self): return self.filename() def filename(self): return os.path.basename(self.file.name)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,773
mrpal39/ev_code
refs/heads/master
/myapi/fullfeblog/blog/urls.py
from django.urls import path from .views import ( PostListView, PostDetailView, # PostCreateView, # PostUpdateView, # PostDeleteView, # UserPostListView ) from . import views from .feeds import LatestPostsFeed urlpatterns = [ path('', views.home, name='home'), path('blogs/', views.PostListView.as_view(), name='post_list'), path('blog/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('about/', views.about, name='about'), path('<int:post_id>/share/',views.post_share, name='post_share'), path('feed/', LatestPostsFeed(), name='post_feed'), path('search/', views.post_search, name='post_search'), path('api/', views.post_api, name='post_api'), path('blog/', views.post_list, name='post_list'), path('<int:year>/<slug:post>/', views.post_detail, name='post_detail'), path('tag/<slug:tag_slug>/', views.post_list, name='post_list_by_tag'), ]
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,774
mrpal39/ev_code
refs/heads/master
/Web-UI/scrapyproject/scrapy_packages/mongodb/scrapy_mongodb.py
# coding:utf-8 import datetime from pymongo import errors from pymongo.mongo_client import MongoClient from pymongo.mongo_replica_set_client import MongoReplicaSetClient from pymongo.read_preferences import ReadPreference from scrapy.exporters import BaseItemExporter try: from urllib.parse import quote except: from urllib import quote def not_set(string): """ Check if a string is None or '' :returns: bool - True if the string is empty """ if string is None: return True elif string == '': return True return False class MongoDBPipeline(BaseItemExporter): """ MongoDB pipeline class """ # Default options config = { 'uri': 'mongodb://localhost:27017', 'fsync': False, 'write_concern': 0, 'database': 'scrapy-mongodb', 'collection': 'items', 'replica_set': None, 'buffer': None, 'append_timestamp': False, 'sharded': False } # Needed for sending acknowledgement signals to RabbitMQ for all persisted items queue = None acked_signals = [] # Item buffer item_buffer = dict() def load_spider(self, spider): self.crawler = spider.crawler self.settings = spider.settings self.queue = self.crawler.engine.slot.scheduler.queue def open_spider(self, spider): self.load_spider(spider) # Configure the connection self.configure() self.spidername = spider.name self.config['uri'] = 'mongodb://' + self.config['username'] + ':' + quote(self.config['password']) + '@' + self.config['uri'] + '/admin' self.shardedcolls = [] if self.config['replica_set'] is not None: self.connection = MongoReplicaSetClient( self.config['uri'], replicaSet=self.config['replica_set'], w=self.config['write_concern'], fsync=self.config['fsync'], read_preference=ReadPreference.PRIMARY_PREFERRED) else: # Connecting to a stand alone MongoDB self.connection = MongoClient( self.config['uri'], fsync=self.config['fsync'], read_preference=ReadPreference.PRIMARY) # Set up the collection self.database = self.connection[spider.name] # Autoshard the DB if self.config['sharded']: db_statuses = self.connection['config']['databases'].find({}) partitioned = [] notpartitioned = [] for status in db_statuses: if status['partitioned']: partitioned.append(status['_id']) else: notpartitioned.append(status['_id']) if spider.name in notpartitioned or spider.name not in partitioned: try: self.connection.admin.command('enableSharding', spider.name) except errors.OperationFailure: pass else: collections = self.connection['config']['collections'].find({}) for coll in collections: if (spider.name + '.') in coll['_id']: if coll['dropped'] is not True: if coll['_id'].index(spider.name + '.') == 0: self.shardedcolls.append(coll['_id'][coll['_id'].index('.') + 1:]) def configure(self): """ Configure the MongoDB connection """ # Set all regular options options = [ ('uri', 'MONGODB_URI'), ('fsync', 'MONGODB_FSYNC'), ('write_concern', 'MONGODB_REPLICA_SET_W'), ('database', 'MONGODB_DATABASE'), ('collection', 'MONGODB_COLLECTION'), ('replica_set', 'MONGODB_REPLICA_SET'), ('buffer', 'MONGODB_BUFFER_DATA'), ('append_timestamp', 'MONGODB_ADD_TIMESTAMP'), ('sharded', 'MONGODB_SHARDED'), ('username', 'MONGODB_USER'), ('password', 'MONGODB_PASSWORD') ] for key, setting in options: if not not_set(self.settings[setting]): self.config[key] = self.settings[setting] def process_item(self, item, spider): """ Process the item and add it to MongoDB :type item: Item object :param item: The item to put into MongoDB :type spider: BaseSpider object :param spider: The spider running the queries :returns: Item object """ item_name = item.__class__.__name__ # If we are working with a sharded DB, the collection will also be sharded if self.config['sharded']: if item_name not in self.shardedcolls: try: self.connection.admin.command('shardCollection', '%s.%s' % (self.spidername, item_name), key={'_id': "hashed"}) self.shardedcolls.append(item_name) except errors.OperationFailure: self.shardedcolls.append(item_name) itemtoinsert = dict(self._get_serialized_fields(item)) if self.config['buffer']: if item_name not in self.item_buffer: self.item_buffer[item_name] = [] self.item_buffer[item_name].append([]) self.item_buffer[item_name].append(0) self.item_buffer[item_name][1] += 1 if self.config['append_timestamp']: itemtoinsert['scrapy-mongodb'] = {'ts': datetime.datetime.utcnow()} self.item_buffer[item_name][0].append(itemtoinsert) if self.item_buffer[item_name][1] == self.config['buffer']: self.item_buffer[item_name][1] = 0 self.insert_item(self.item_buffer[item_name][0], spider, item_name) return item self.insert_item(itemtoinsert, spider, item_name) return item def close_spider(self, spider): """ Method called when the spider is closed :type spider: BaseSpider object :param spider: The spider running the queries :returns: None """ for key in self.item_buffer: if self.item_buffer[key][0]: self.insert_item(self.item_buffer[key][0], spider, key) def insert_item(self, item, spider, item_name): """ Process the item and add it to MongoDB :type item: (Item object) or [(Item object)] :param item: The item(s) to put into MongoDB :type spider: BaseSpider object :param spider: The spider running the queries :returns: Item object """ self.collection = self.database[item_name] if not isinstance(item, list): if self.config['append_timestamp']: item['scrapy-mongodb'] = {'ts': datetime.datetime.utcnow()} ack_signal = item['ack_signal'] item.pop('ack_signal', None) self.collection.insert(item, continue_on_error=True) if ack_signal not in self.acked_signals: self.queue.acknowledge(ack_signal) self.acked_signals.append(ack_signal) else: signals = [] for eachitem in item: signals.append(eachitem['ack_signal']) eachitem.pop('ack_signal', None) self.collection.insert(item, continue_on_error=True) del item[:] for ack_signal in signals: if ack_signal not in self.acked_signals: self.queue.acknowledge(ack_signal) self.acked_signals.append(ack_signal)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,775
mrpal39/ev_code
refs/heads/master
/awssam/fullfeblog/blog/feeds.py
from django.contrib.syndication.views import Feed from django.template.defaultfilters import truncatewords from django.urls import reverse_lazy from .models import Post class LatestPostsFeed(Feed): title ='My Blog' link=reverse_lazy('post_list') description = 'new post of my Blog.' def items(self): return Post.published.all()[:5] def item_title(self, item): return super().item_title(item) def item_description(self, item): return truncatewords(item.body,30)
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,776
mrpal39/ev_code
refs/heads/master
/awssam/tutorial/api.py
import http.client conn = http.client.HTTPSConnection("bloomberg-market-and-financial-news.p.rapidapi.com") headers = { 'x-rapidapi-key': "bd689f15b2msh55122d4390ca494p17cddcjsn225c43ecc6d4", 'x-rapidapi-host': "bloomberg-market-and-financial-news.p.rapidapi.com" } conn.request("GET", "/market/get-cross-currencies?id=aed%2Caud%2Cbrl%2Ccad%2Cchf%2Ccnh%2Ccny%2Ccop%2Cczk%2Cdkk%2Ceur%2Cgbp%2Chkd%2Chuf%2Cidr%2Cils%2Cinr%2Cjpy%2Ckrw%2Cmxn%2Cmyr%2Cnok%2Cnzd%2Cphp%2Cpln%2Crub%2Csek%2Csgd%2Cthb%2Ctry%2Ctwd%2Cusd%2Czar", headers=headers) res = conn.getresponse() data = res.read() # print(data.decode("utf-8")) print(data.json())
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,777
mrpal39/ev_code
refs/heads/master
/awssam/django-blog/src/blog/urls.py
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: urls.py Description : Author : JHao date: 2017/4/13 ------------------------------------------------- Change Activity: 2017/4/13: ------------------------------------------------- """ __author__ = 'JHao' from blog import views from django.urls import path urlpatterns = [ path('', views.index, name='index'), path('list/', views.blog_list, name='list'), path('tag/<str:name>/', views.tag, name='tag'), path('category/<str:name>/', views.category, name='category'), path('detail/<int:pk>/', views.detail, name='detail'), path('archive/', views.archive, name='archive'), path('search/', views.search, name='search'), path('message/', views.message, name='message'), path('getComment/', views.get_comment, name='get_comment'), ]
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,778
mrpal39/ev_code
refs/heads/master
/scrap/properties/properties/items.py
from scrapy.item import Item, Field import datetime import socket class PropertiesItem(Item): # Primary fields title = PropertiesItem() price = Field() description = Field() address = Field() image_urls = Field() # Calculated fields images = Field() location = Field() # Housekeeping fields l.add_value('url', response.url) l.add_value('project', self.settings.get('BOT_NAME')) l.add_value('spider', self.name) l.add_value('server', socket.gethostname()) l.add_value('date', datetime.datetime.now()) return l.load_item()
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,779
mrpal39/ev_code
refs/heads/master
/cte/properties/properties/spiders/basic.py
import scrapy from properties.items import PropertiesItem from scrapy.loader import ItemLoader from itemloaders.processors import MapCompose, Join class BasicSpider(scrapy.Spider): name = 'basic' allowed_domains = ['web'] start_urls = ['http://web:9312/properties/property_000000.html'] def parse(self, response): #Cleaning up – item loaders and housekeeping fields l = ItemLoader(item=PropertiesItem(), response=response) l.add_xpath("title", '//*[@itemprop="name"][1]/text()' ,MapCompose(unicode.strip, unicode.title)) l.add_xpath("price", '//*[@itemprop="price"][1]/text()',MapCompose(lambda i: i.replace(',', ''), float),re('[0.9]+') l.add_xpath("description", '//*[@itemprop="description"][1]/text()', MapCompose(unicode.strip), Join()) l.add_xpath("address ", '//*[@itemtype="http://schema.org/Place"][1]/text()',MapCompose(unicode.strip)) l.add_xpath("image_urls", '//*[@itemprop="image"][1]/@src', MapCompose(lambda i: urlparse.urljoin(response.url, i))) return l.load_item() # def parse(self, response): # item = PropertiesItem() # item['title'] = response.xpath( # '//*[@itemprop="list-group-item"][1]/text()').extract() # item['price'] = response.xpath('//*[@itemprop="price"][1]/text()').re('[.0-9]+') # item['description'] = response.xpath('//*[@itemprop="description"][1]/text()').extract() # return item # def parse(self, response): # self.log("title:%s"%response.xpath( # '//*[@itemprop="name"][1]/text()').extract() # ) # self.log("price:%s" % response.xpath( # '//*[@itemprop="price"][1]/text()').re('[0.9]+')) # self.log("description: %s" % response.xpath( # '//*[@itemprop="description"][1]/text()').extract()) # self.log("address: %s" % response.xpath( # '//*[@itemtype="http://schema.org/Place"][1]/text()').extract()) # self.log("image_urls: %s" % response.xpath('//*[@itemprop="image"][1]/@src').extract())
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,780
mrpal39/ev_code
refs/heads/master
/awssam/django-blog/src/django_blog/util.py
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: util Description : Author : JHao date: 2020/9/30 ------------------------------------------------- Change Activity: 2020/9/30: ------------------------------------------------- """ __author__ = 'JHao' from math import ceil class PageInfo(object): def __init__(self, page, total, limit=8): """ :param page: 页数 :param total: 总条数 :param limit: 每页条数 """ self._limit = limit self._total = total self._page = page self._index_start = (int(page) - 1) * int(limit) self._index_end = int(page) * int(limit) @property def index_start(self): return self._index_start @property def index_end(self): return self._index_end @property def current_page(self): return self._page @property def total_page(self): return ceil(self._total / self._limit) @property def total_number(self): return self._total
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,781
mrpal39/ev_code
refs/heads/master
/scrap/tuto/tuto/pipelines.py
import collections from scrapy.exceptions import DropItem from scrapy.exceptions import DropItem import pymongo class TutoPipeline(object): vat=2.55 def process_item(self, item, spider): if item["price"]: if item['exclues_vat']: item['price']= item['price']*self.vat return item else: raise DropItem("missing price in %s"% item) return item class MongoPipline(object): collections_name='scrapy_list' def __init__(self,mongo_uri,mongo_db): self.mongo_uri= mongo_uri self.mongo_db=mongo_db @classmethod def from_crewler(cls,crawler): return cls( mongo_uri=crawler.settings.get('MONGO_URI'), mongo_db=crawler.settings.get('MONGO_DB','Lists') ) def open_spider(self,spider): self.client=pymongo.MongoClient(self.mongo_uri) self.db=self.client[self.mongo_db] def close_spider(self,spider): self.client.close() def process_item(self,item,spider): self.db[self.collection_name].insert(dict(item)) return item # You can specify the MongoDB address and # database name in Scrapy settings and MongoDB # collection can be named after the item class. # The following code describes # how to use from_crawler() method to collect the resources properly − class DuplicatePiline(object): def __init__(self): self.ids_seen=set() def process_item(self,item,spider): if item['id' ] in self.ids_seen: raise DropItem("Repacted Item Found:%s"%item) else: self.ids_seen.add(item['id']) return item
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,782
mrpal39/ev_code
refs/heads/master
/tc_zufang/tc_zufang/tc_zufang/settings.py
# -*- coding: utf-8 -*- BOT_NAME = 'tc_zufang' SPIDER_MODULES = ['tc_zufang.spiders'] NEWSPIDER_MODULE = 'tc_zufang.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'tc_zufang (+http://www.yourdomain.com)' #item Pipeline同时处理item的最大值为100 # CONCURRENT_ITEMS=100 #scrapy downloader并发请求最大值为16 #CONCURRENT_REQUESTS=4 #对单个网站进行并发请求的最大值为8 #CONCURRENT_REQUESTS_PER_DOMAIN=2 #抓取网站的最大允许的抓取深度值 DEPTH_LIMIT=0 # Obey robots.txt rules ROBOTSTXT_OBEY = True DOWNLOAD_TIMEOUT=10 DNSCACHE_ENABLED=True #避免爬虫被禁的策略1,禁用cookie # Disable cookies (enabled by default) COOKIES_ENABLED = False CONCURRENT_REQUESTS=4 #CONCURRENT_REQUESTS_PER_IP=2 #CONCURRENT_REQUESTS_PER_DOMAIN=2 #设置下载延时,防止爬虫被禁 DOWNLOAD_DELAY = 5 DOWNLOADER_MIDDLEWARES = { 'scrapy.contrib.downloadermiddleware.httpproxy.HttpProxyMiddleware': 110, "tc_zufang.Proxy_Middleware.ProxyMiddleware":100, 'scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware': 100, 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware': 550, 'scrapy.downloadermiddlewares.ajaxcrawl.AjaxCrawlMiddleware': 560, 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 590, 'scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware': 830, 'scrapy.downloadermiddlewares.stats.DownloaderStats': 850, 'tc_zufang.timeout_middleware.Timeout_Middleware':610, 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware': None, 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': 300, 'scrapy.downloadermiddlewares.retry.RetryMiddleware': None, 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware': None, 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware': 400, 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware': None, 'scrapy.downloadermiddlewares.httpcache.HttpCacheMiddleware': None, 'tc_zufang.rotate_useragent_dowmloadmiddleware.RotateUserAgentMiddleware':400, 'tc_zufang.redirect_middleware.Redirect_Middleware':500, } #使用scrapy-redis组件,分布式运行多个爬虫 #配置日志存储目录 SCHEDULER = "scrapy_redis.scheduler.Scheduler" DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter" SCHEDULER_PERSIST = True SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.SpiderPriorityQueue' REDIS_URL = None REDIS_HOST = '127.0.0.1' # 也可以根据情况改成 localhost REDIS_PORT = '6379' #LOG_FILE = "logs/scrapy.log"
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,783
mrpal39/ev_code
refs/heads/master
/myapi/devfile/blog/urls.py
from django.urls import path,include from blog import views urlpatterns = [ # path('', views.index, name='base'), path('', views.list, name='list'), # path('home/', views.home, name='home'), # path('search/', views.Search, name='home_search'), # path('', views.home, name='home'), ]
{"/awssam/iam/users/urls.py": ["/awssam/iam/users/views.py"], "/myapi/devfile/core/views.py": ["/myapi/devfile/core/forms.py"], "/Web-UI/scrapyproject/views.py": ["/Web-UI/scrapyproject/forms.py", "/Web-UI/scrapyproject/models.py"], "/awssam/ideablog/core/admin.py": ["/awssam/ideablog/core/models.py"], "/awssam/wikidj/wikidj/codehilite.py": ["/awssam/wikidj/wikidj/settings.py", "/awssam/wikidj/wikidj/dev.py"], "/awssam/ideablog/core/views.py": ["/awssam/ideablog/core/models.py"], "/myapi/fullfeblog/blog/search_indexes.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/templatetags/blog_tags.py": ["/myapi/fullfeblog/blog/models.py"], "/myapi/fullfeblog/blog/views.py": ["/myapi/fullfeblog/blog/models.py", "/myapi/fullfeblog/blog/forms.py"], "/awssam/wikidj/wikidj/dev.py": ["/awssam/wikidj/wikidj/settings.py"], "/tc_zufang/django_web/datashow/views.py": ["/tc_zufang/django_web/datashow/models.py"], "/awssam/ideablog/core/forms.py": ["/awssam/ideablog/core/models.py"], "/Web-UI/scrapyproject/admin.py": ["/Web-UI/scrapyproject/models.py"], "/myapi/fullfeblog/blog/urls.py": ["/myapi/fullfeblog/blog/views.py"]}
3,826
hdoupe/Matchups
refs/heads/master
/data/build_data.py
import pandas as pd # people from: https://raw.githubusercontent.com/chadwickbureau/register/master/data/people.csv # sc from: from pybaseball import statcast sc = statcast(start_dt="2012-01-01", end_dt="2021-01-01") sc.to_parquet("statcast_dump.parquet", engine="fastparquet") people = pd.read_csv("github://chadwickbureau:register@master/data/people.csv") # sc = pd.read_parquet("statcast_dump.parquet", engine="fastparquet") people["batter_name"] = people.name_first + " " + people.name_last merged = pd.merge( sc, people.loc[:, ["key_mlbam", "batter_name"]], how="left", left_on="batter", right_on="key_mlbam", ) cols2keep = [ "player_name", "batter_name", "pitch_type", "game_date", "release_speed", "events", "launch_speed", "woba_value", "bb_type", "balls", "strikes", "outs_when_up", "at_bat_number", "type", "plate_x", "plate_z", "stand", ] sc = merged.loc[:, cols2keep] sc.to_parquet("statcast.parquet", engine="pyarrow") sc["date"] = pd.to_datetime(merged["game_date"]) recent = sc.loc[sc.date > "2020-01-01", :] recent.drop(columns=["date"], inplace=True) recent.to_parquet("statcast_recent.parquet", engine="pyarrow")
{"/matchups/__init__.py": ["/matchups/matchups.py", "/matchups/utils.py"], "/matchups/matchups.py": ["/matchups/utils.py", "/matchups/__init__.py"], "/matchups/tests/test_outputs.py": ["/matchups/__init__.py"], "/matchups/tests/test_inputs.py": ["/matchups/__init__.py"], "/cs-config/cs_config/functions.py": ["/matchups/__init__.py"]}
3,827
hdoupe/Matchups
refs/heads/master
/cs-config/cs_config/tests/test_functions.py
from cs_kit import CoreTestFunctions from cs_config import functions class TestFunctions1(CoreTestFunctions): get_version = functions.get_version get_inputs = functions.get_inputs validate_inputs = functions.validate_inputs run_model = functions.run_model ok_adjustment = { "matchup": { "pitcher": [{"value": "Max Scherzer"}], "batter": [{"value": ["Freddie Freeman"]}], "start_date": [{"value": "2020-10-19T04:00:00.000Z"}], } } bad_adjustment = {"matchup": {"pitcher": [{"value": "Not a pitcher"}]}}
{"/matchups/__init__.py": ["/matchups/matchups.py", "/matchups/utils.py"], "/matchups/matchups.py": ["/matchups/utils.py", "/matchups/__init__.py"], "/matchups/tests/test_outputs.py": ["/matchups/__init__.py"], "/matchups/tests/test_inputs.py": ["/matchups/__init__.py"], "/cs-config/cs_config/functions.py": ["/matchups/__init__.py"]}
3,828
hdoupe/Matchups
refs/heads/master
/matchups/__init__.py
name = "matchups" __version__ = "2021" from matchups.matchups import * from matchups.utils import *
{"/matchups/__init__.py": ["/matchups/matchups.py", "/matchups/utils.py"], "/matchups/matchups.py": ["/matchups/utils.py", "/matchups/__init__.py"], "/matchups/tests/test_outputs.py": ["/matchups/__init__.py"], "/matchups/tests/test_inputs.py": ["/matchups/__init__.py"], "/cs-config/cs_config/functions.py": ["/matchups/__init__.py"]}
3,829
hdoupe/Matchups
refs/heads/master
/matchups/utils.py
import json import os CURRENT_PATH = os.path.abspath(os.path.dirname(__file__)) def get_choices(): with open(os.path.join(CURRENT_PATH, "playerchoices.json")) as f: return json.loads(f.read()) def pdf_to_clean_html(pdf): """Takes a PDF and returns an HTML table without any deprecated tags or irrelevant styling""" return (pdf.to_html() .replace(' border="1"', '') .replace(' style="text-align: right;"', '')) def renamedf(df, normalized=True): index_map = { "balls": "Balls", "strikes": "Strikes", "type": "Pitch Outcome", "pitch_type": "Pitch Type", } template_col_map = { "type": "{op} of pitch outcome by count", "pitch_type": "{op} of pitch type by count", } if normalized: op = "Proportion" else: op = "Count" # rename index df.index.names = [index_map[oldname] for oldname in df.index.names] col_map = {} for oldname, newname in template_col_map.items(): if oldname in df.columns: col_map[oldname] = newname.format(op=op) return df.rename(columns=col_map)
{"/matchups/__init__.py": ["/matchups/matchups.py", "/matchups/utils.py"], "/matchups/matchups.py": ["/matchups/utils.py", "/matchups/__init__.py"], "/matchups/tests/test_outputs.py": ["/matchups/__init__.py"], "/matchups/tests/test_inputs.py": ["/matchups/__init__.py"], "/cs-config/cs_config/functions.py": ["/matchups/__init__.py"]}
3,830
hdoupe/Matchups
refs/heads/master
/matchups/matchups.py
import json import os from datetime import datetime, date from bokeh.plotting import figure, show from bokeh.models import ColumnDataSource from bokeh.embed import json_item from bokeh.palettes import d3 from bokeh.models.widgets import Tabs, Panel import pandas as pd import numpy as np import paramtools import marshmallow as ma from marshmallow import ValidationError from matchups.utils import CURRENT_PATH, renamedf, pdf_to_clean_html from matchups import __version__ CURRENT_PATH = os.path.abspath(os.path.dirname(__file__)) def count_plot(df, title): p = figure(title=title, match_aspect=True) p.grid.visible = False strike_zone_cds = ColumnDataSource( { "x": [-8.5 / 12, 8.5 / 12], "x_side1": [-8.5 / 12, -8.5 / 12], "x_side2": [8.5 / 12, 8.5 / 12], "top": [3.0, 3.0], "bottom": [1.2, 1.2], "side1": [3.0, 1.2], "side2": [1.2, 3.0], } ) p.line(x="x", y="top", line_width=3, color="red", source=strike_zone_cds) p.line(x="x", y="bottom", line_width=3, color="red", source=strike_zone_cds) p.line(x="x_side1", y="side1", line_width=3, color="red", source=strike_zone_cds) p.line(x="x_side2", y="side2", line_width=3, color="red", source=strike_zone_cds) pitch_types = df.pitch_type.unique() palette = d3["Category20"][max(3, pitch_types.shape[0])] for ix, (pitch_type, df) in enumerate(df.groupby("pitch_type")): p.circle( -df.plate_x, df.plate_z, legend_label=pitch_type, color=palette[ix], size=10, alpha=1, muted_color=palette[ix], muted_alpha=0.2, ) p.legend.click_policy = "hide" return p def count_panels(df, main_title): p = count_plot(df, main_title) panels = [Panel(child=p, title="All counts")] for (balls, strikes), df in df.groupby(["balls", "strikes"]): panels.append( Panel( child=count_plot( df, f"{main_title} (balls={balls}, strikes={strikes})" ), title=f"{balls}-{strikes}", ) ) tabs = Tabs(tabs=panels) return tabs def append_output(df, title, renderable, downloadable): if len(df) == 0: renderable.append( { "media_type": "table", "title": title, "data": "<p><b>No matchups found.</b></p>", } ) else: data = json_item(count_panels(df, title)) renderable.append({"media_type": "bokeh", "title": title, "data": data}) downloadable.append({"media_type": "CSV", "title": title, "data": df.to_csv()}) class MetaParams(paramtools.Parameters): array_first = True defaults = { "use_full_sample": { "title": "Use Full Data", "description": "Flag that determines whether Matchups uses the 10 year data set or the 2020 data set.", "type": "bool", "value": True, "validators": {"choice": {"choices": [True, False]}}, } } class MatchupsParams(paramtools.Parameters): defaults_template = os.path.join(CURRENT_PATH, "defaults.json") def __init__(self, *args, **kwargs): players = pd.read_parquet( os.path.join(CURRENT_PATH, "players.parquet"), engine="fastparquet" ) with open(self.defaults_template, "r") as f: self.defaults = json.loads(f.read()) self.defaults["pitcher"]["validators"]["choice"]["choices"] = [ "Max Scherzer" ] + players.players.tolist() self.defaults["batter"]["validators"]["choice"]["choices"] = [ "Freddie Freeman" ] + players.players.tolist() super().__init__(*args, **kwargs) def get_inputs(meta_params_dict): meta_params = MetaParams() meta_params.adjust(meta_params_dict) params = MatchupsParams() params.set_state(use_full_sample=meta_params.use_full_sample.tolist()) # Drop choice lists to reduce JSON size. matchup_params = params.dump() matchup_params["pitcher"]["validators"] = {} matchup_params["batter"]["validators"] = {} return { "meta_parameters": meta_params.dump(), "model_parameters": {"matchup": matchup_params}, } def fixup_dates(adjustment): adj = adjustment["matchup"] for var in ["start_date", "end_date"]: if var in adj: if not isinstance(adj[var], list): adj[var] = [{"value": adj[var]}] for value in adj[var]: try: value["value"] = ( ma.fields.DateTime() ._deserialize(value["value"], None, None) .date() ) except Exception as e: print("exception parsing:", value) print(e) pass def validate_inputs(meta_param_dict, adjustment, errors_warnings): # matchups doesn't look at meta_param_dict for validating inputs. params = MatchupsParams() fixup_dates(adjustment) params.adjust(adjustment["matchup"], raise_errors=False) errors_warnings["matchup"]["errors"].update(params.errors) return {"errors_warnings": errors_warnings} def get_matchup(meta_param_dict, adjustment): meta_params = MetaParams() meta_params.adjust(meta_param_dict) params = MatchupsParams() params.set_state(use_full_sample=meta_params.use_full_sample.tolist()) fixup_dates(adjustment) params.adjust(adjustment["matchup"]) print( "getting data according to: ", meta_params.specification(), params.specification(), ) if meta_params.use_full_sample: path = os.path.join(CURRENT_PATH, "statcast.parquet") else: path = os.path.join(CURRENT_PATH, "statcast_recent.parquet") scall = pd.read_parquet(path, engine="fastparquet") print("data read") scall["date"] = pd.to_datetime(scall["game_date"]) sc = scall.loc[ (scall.date >= pd.Timestamp(params.start_date[0]["value"])) & (scall.date < pd.Timestamp(params.end_date[0]["value"])) ] print("filtered by date") pitcher, batters = params.pitcher[0]["value"], params.batter[0]["value"] renderable = [] downloadable = [] pitcher_df = sc.loc[(scall["player_name"] == pitcher), :] append_output(pitcher_df, f"{pitcher} v. All batters", renderable, downloadable) for batter in batters: batter_df = pitcher_df.loc[ (scall["player_name"] == pitcher) & (scall["batter_name"] == batter), : ] append_output(batter_df, f"{pitcher} v. {batter}", renderable, downloadable) return {"renderable": renderable, "downloadable": downloadable}
{"/matchups/__init__.py": ["/matchups/matchups.py", "/matchups/utils.py"], "/matchups/matchups.py": ["/matchups/utils.py", "/matchups/__init__.py"], "/matchups/tests/test_outputs.py": ["/matchups/__init__.py"], "/matchups/tests/test_inputs.py": ["/matchups/__init__.py"], "/cs-config/cs_config/functions.py": ["/matchups/__init__.py"]}
3,831
hdoupe/Matchups
refs/heads/master
/data/write_players.py
import pandas as pd people = pd.read_csv("github://chadwickbureau:register@master/data/people.csv") people = people.loc[people.mlb_played_last > 2009, :] all_players = pd.DataFrame.from_dict( {"players": sorted((people.name_first + " " + people.name_last).dropna().unique())} ) all_players.to_parquet("../matchups/players.parquet", engine="fastparquet")
{"/matchups/__init__.py": ["/matchups/matchups.py", "/matchups/utils.py"], "/matchups/matchups.py": ["/matchups/utils.py", "/matchups/__init__.py"], "/matchups/tests/test_outputs.py": ["/matchups/__init__.py"], "/matchups/tests/test_inputs.py": ["/matchups/__init__.py"], "/cs-config/cs_config/functions.py": ["/matchups/__init__.py"]}
3,832
hdoupe/Matchups
refs/heads/master
/matchups/tests/test_outputs.py
import matchups def test_get_matchup(): adj = { "matchup": { "batter": [{"value": ["Freddie Freeman"], "use_full_sample": False}] } } assert matchups.get_matchup({"use_full_sample": False}, adj) def test_get_matchup_empty(): adj = { "matchup": {"pitcher": [{"value": "Freddie Freeman", "use_full_sample": False}]} } assert matchups.get_matchup({"use_full_sample": False}, adj)
{"/matchups/__init__.py": ["/matchups/matchups.py", "/matchups/utils.py"], "/matchups/matchups.py": ["/matchups/utils.py", "/matchups/__init__.py"], "/matchups/tests/test_outputs.py": ["/matchups/__init__.py"], "/matchups/tests/test_inputs.py": ["/matchups/__init__.py"], "/cs-config/cs_config/functions.py": ["/matchups/__init__.py"]}
3,833
hdoupe/Matchups
refs/heads/master
/matchups/tests/test_inputs.py
import matchups def test_MatchupsParams(): params = matchups.MatchupsParams() assert params def test_update_params(): params = matchups.MatchupsParams() adj = {"batter": [{"use_full_sample": False, "value": ["Alex Rodriguez"]}]} params.adjust(adj) params.set_state(use_full_sample=False) assert params.batter == adj["batter"] def test_parse_inputs(): meta_params = {"use_full_sample": True} adj = {"matchup": {"batter": ["Alex Rodriguez"]}} ew = {"matchup": {"errors": {}, "warnings": {}}} assert matchups.validate_inputs(meta_params, adj, ew) def test_parse_bad_inputs(): meta_params = {"use_full_sample": True} adj = {"matchup": {"batter": [1], "pitcher": 1234,}} ew = {"matchup": {"errors": {}, "warnings": {}}} ew = matchups.validate_inputs(meta_params, adj, ew) ew = ew["errors_warnings"] assert ew["matchup"]["errors"]["batter"] == ["Not a valid string."] assert ew["matchup"]["errors"]["pitcher"] == ["Not a valid string."] adj = {"matchup": {"batter": ["fake batter"],}} ew = {"matchup": {"errors": {}, "warnings": {}}} ew = matchups.validate_inputs(meta_params, adj, ew) ew = ew["errors_warnings"] exp = ['batter "fake batter" must be in list of choices.'] assert ew["matchup"]["errors"]["batter"] == exp
{"/matchups/__init__.py": ["/matchups/matchups.py", "/matchups/utils.py"], "/matchups/matchups.py": ["/matchups/utils.py", "/matchups/__init__.py"], "/matchups/tests/test_outputs.py": ["/matchups/__init__.py"], "/matchups/tests/test_inputs.py": ["/matchups/__init__.py"], "/cs-config/cs_config/functions.py": ["/matchups/__init__.py"]}
3,834
hdoupe/Matchups
refs/heads/master
/cs-config/cs_config/functions.py
import matchups def get_version(): return matchups.__version__ def get_inputs(meta_param_dict): return matchups.get_inputs(meta_param_dict) def validate_inputs(meta_param_dict, adjustment, errors_warnings): return matchups.validate_inputs(meta_param_dict, adjustment, errors_warnings) def run_model(meta_param_dict, adjustment): return matchups.get_matchup(meta_param_dict, adjustment)
{"/matchups/__init__.py": ["/matchups/matchups.py", "/matchups/utils.py"], "/matchups/matchups.py": ["/matchups/utils.py", "/matchups/__init__.py"], "/matchups/tests/test_outputs.py": ["/matchups/__init__.py"], "/matchups/tests/test_inputs.py": ["/matchups/__init__.py"], "/cs-config/cs_config/functions.py": ["/matchups/__init__.py"]}
3,877
daratovstyga/web_http
refs/heads/master
/search.py
import sys from io import BytesIO import requests from PIL import Image import get_ap from get_cord import get_cord ll = get_cord() org = get_ap.get_ap(ll)[0] map_params = { "ll": ll, "l": "map", "pt": ll + ',round' + '~' + ','.join(map(str, org[3])) + ',comma' } map_api_server = "http://static-maps.yandex.ru/1.x/" response = requests.get(map_api_server, params=map_params) print(f'Адрес: {org[2]}\nНазвание: {org[1]}\nВремя работы: {org[4]}\nРасстояние: {org[0]} м.') if not response: print("Ошибка выполнения запроса:") print("Http статус:", response.status_code, "(", response.reason, ")") sys.exit(1) else: Image.open(BytesIO(response.content)).show()
{"/search.py": ["/get_ap.py", "/get_cord.py"], "/district.py": ["/get_cord.py"], "/guessing_game.py": ["/get_cord_new.py"], "/10ap.py": ["/get_cord.py", "/get_ap.py"]}
3,878
daratovstyga/web_http
refs/heads/master
/get_cord.py
import sys import requests def get_cord(): # toponym_to_find = "Москва, ул. Ак. Королева, 12" toponym_to_find = " ".join(sys.argv[1:]) geocoder_api_server = "http://geocode-maps.yandex.ru/1.x/" geocoder_params = { "apikey": "40d1649f-0493-4b70-98ba-98533de7710b", "geocode": toponym_to_find, "format": "json"} response = requests.get(geocoder_api_server, params=geocoder_params) if not response: print("Ошибка выполнения запроса:") print("Http статус:", response.status_code, "(", response.reason, ")") sys.exit(1) else: json_response = response.json() toponym = json_response["response"]["GeoObjectCollection"]["featureMember"][0]["GeoObject"] return ','.join(toponym['Point']['pos'].split())
{"/search.py": ["/get_ap.py", "/get_cord.py"], "/district.py": ["/get_cord.py"], "/guessing_game.py": ["/get_cord_new.py"], "/10ap.py": ["/get_cord.py", "/get_ap.py"]}
3,879
daratovstyga/web_http
refs/heads/master
/district.py
import sys import requests from get_cord import get_cord ll = get_cord() geocoder_api_server = "http://geocode-maps.yandex.ru/1.x/" geocoder_params = { "apikey": "40d1649f-0493-4b70-98ba-98533de7710b", "geocode": ll, "kind": 'district', "format": "json"} response = requests.get(geocoder_api_server, params=geocoder_params) if not response: print("Ошибка выполнения запроса:") print("Http статус:", response.status_code, "(", response.reason, ")") sys.exit(1) else: json_response = response.json() print(json_response["response"]["GeoObjectCollection"]["featureMember"][0]["GeoObject"]["metaDataProperty"]["GeocoderMetaData"]["text"])
{"/search.py": ["/get_ap.py", "/get_cord.py"], "/district.py": ["/get_cord.py"], "/guessing_game.py": ["/get_cord_new.py"], "/10ap.py": ["/get_cord.py", "/get_ap.py"]}
3,880
daratovstyga/web_http
refs/heads/master
/guessing_game.py
import os import sys import random import pygame import requests from get_cord_new import get_cord map_files = [] cities = ['Москва', 'Курган', 'Санкт-Петербург', 'Владивосток', 'Калининград'] pos = [get_cord(i) for i in cities] for i in range(len(pos)): map_params = {"ll": pos[i][0], "spn": pos[i][1], "size": '600,450', "l": random.choice(["map", "sat"])} map_api_server = "http://static-maps.yandex.ru/1.x/" response = requests.get(map_api_server, params=map_params) if not response: print("Ошибка выполнения запроса:") print(response.url) print("Http статус:", response.status_code, "(", response.reason, ")") sys.exit(1) else: map_file = "map.png" with open(map_file, "wb") as file: file.write(response.content) map_files.append(pygame.image.load(map_file)) os.remove(map_file) i = 0 random.shuffle(map_files) pygame.init() screen = pygame.display.set_mode((600, 450)) screen.blit(map_files[i], (0, 0)) pygame.display.flip() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: i = (i + 1) % len(map_files) screen.blit(map_files[i], (0, 0)) pygame.display.flip() pygame.quit()
{"/search.py": ["/get_ap.py", "/get_cord.py"], "/district.py": ["/get_cord.py"], "/guessing_game.py": ["/get_cord_new.py"], "/10ap.py": ["/get_cord.py", "/get_ap.py"]}
3,881
daratovstyga/web_http
refs/heads/master
/get_ap.py
import math import sys import requests def dist(cord1, cord2): dx = abs(cord1[0] - cord2[0]) * 111 * 1000 * math.cos(math.radians((cord1[1] + cord2[1]) / 2)) dy = abs(cord1[1] - cord2[1]) * 111 * 1000 return int((dx * dx + dy * dy) ** 0.5) def get_ap(ll, k=1): ll_float = list(map(float, ll.split(','))) search_api_server = "https://search-maps.yandex.ru/v1/" api_key = "920e2579-8aef-445d-a34d-ed523688c844" search_params = { "apikey": api_key, "text": "аптека", "lang": "ru_RU", "ll": ll, "type": "biz", "results": 100 } response = requests.get(search_api_server, params=search_params) if not response: print("Ошибка выполнения запроса:") print("Http статус:", response.status_code, "(", response.reason, ")") sys.exit(1) else: json_response = response.json() list1 = [] for organization in json_response["features"]: org_name = organization["properties"]["CompanyMetaData"]["name"] org_address = organization["properties"]["CompanyMetaData"]["address"] org_point = organization["geometry"]["coordinates"] if 'Hours' in organization['properties']['CompanyMetaData']: org_times = organization['properties']['CompanyMetaData']['Hours']['text'] else: org_times = '' org_dist = dist(ll_float, org_point) list1.append((org_dist, org_name, org_address, org_point, org_times)) return list(sorted(list1, key=lambda x: (x[0], x[1], x[2], x[3], x[4])))[:k]
{"/search.py": ["/get_ap.py", "/get_cord.py"], "/district.py": ["/get_cord.py"], "/guessing_game.py": ["/get_cord_new.py"], "/10ap.py": ["/get_cord.py", "/get_ap.py"]}
3,882
daratovstyga/web_http
refs/heads/master
/10ap.py
import sys from io import BytesIO import requests from PIL import Image from get_cord import get_cord import get_ap ll = get_cord() info = get_ap.get_ap(ll, 10) rc = ',pm2gnm~'.join([','.join(map(str, org[3])) for org in info if org[4] == 'круглосуточно']) if rc: rc += ',pm2gnm~' rcn = ',pm2blm~'.join([','.join(map(str, org[3])) for org in info if org[4]]) if rcn: rcn += ',pm2blm~' no_data = ',pm2grm~'.join([','.join(map(str, org[3])) for org in info if org[4] == '']) if no_data: no_data += ',pm2grm' map_params = { "ll": ll, "l": "map", "pt": rc + rcn + no_data } map_api_server = "http://static-maps.yandex.ru/1.x/" response = requests.get(map_api_server, params=map_params) if not response: print("Ошибка выполнения запроса:") print("Http статус:", response.status_code, "(", response.reason, ")") sys.exit(1) else: Image.open(BytesIO(response.content)).show()
{"/search.py": ["/get_ap.py", "/get_cord.py"], "/district.py": ["/get_cord.py"], "/guessing_game.py": ["/get_cord_new.py"], "/10ap.py": ["/get_cord.py", "/get_ap.py"]}
3,883
daratovstyga/web_http
refs/heads/master
/get_cord_new.py
import sys import requests def optimal_spn(toponym): to = toponym["boundedBy"]["Envelope"] lc = list(map(float, to["lowerCorner"].split())) uc = list(map(float, to["upperCorner"].split())) spn = ','.join([str(abs(uc[0] - lc[0]) / 50), str(abs(uc[1] - lc[1]) / 50)]) return spn def get_cord(toponym_to_find): geocoder_api_server = "http://geocode-maps.yandex.ru/1.x/" geocoder_params = { "apikey": "40d1649f-0493-4b70-98ba-98533de7710b", "geocode": toponym_to_find, "format": "json"} response = requests.get(geocoder_api_server, params=geocoder_params) if not response: print("Ошибка выполнения запроса:") print("Http статус:", response.status_code, "(", response.reason, ")") sys.exit(1) else: json_response = response.json() toponym = json_response["response"]["GeoObjectCollection"]["featureMember"][0]["GeoObject"] spn = optimal_spn(toponym) return (','.join(toponym['Point']['pos'].split()), spn)
{"/search.py": ["/get_ap.py", "/get_cord.py"], "/district.py": ["/get_cord.py"], "/guessing_game.py": ["/get_cord_new.py"], "/10ap.py": ["/get_cord.py", "/get_ap.py"]}
3,884
chengyan1984/cdk-gui
refs/heads/master
/ConkaUtil.py
import json from urllib.parse import urlparse import requests class ConkaUtil: def __init__(self, username, passwd, adminid='15870', factoryid='1', baseurl='https://crm.konka.com', bjdomain='http://north.bangjia.me'): parsed_uri = urlparse(baseurl) self.host = parsed_uri.netloc self.username = username self.passwd = passwd self.baseurl = baseurl self.adminid = adminid self.factoryid = factoryid self.bjdomain = bjdomain self.mainurl = self.baseurl + '/admin/page!main.action' self.searchurl = self.baseurl + '/afterservice/afterservice!api.action' self.session = requests.Session() self.agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' \ 'Chrome/81.0.4044.113 Safari/537.36' self.datasuccess = {'code': 1, 'msg': '抓单成功', 'element': ''} self.datafail = {'code': 0, 'msg': '抓单失败,请确认账号密码是否正确'} self.headers = {'Content-Type': 'application/json;charset=UTF-8', 'User-Agent': self.agent, 'Upgrade-Insecure-Requests': '1', 'Host': self.host, 'Origin': self.baseurl, 'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive', 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2', 'Accept': 'application/json, text/plain, */*'} def loadMain(self): loginurl = self.baseurl + "/services/organization/api/authenticate" data = {"username": self.username, "password": self.passwd, "rememberMe": True} self.headers['Referer'] = self.baseurl response = self.session.post(loginurl, headers=self.headers, data=json.dumps(data)) response.encoding = 'utf-8' author = response.headers['Authorization'] self.headers['Authorization'] = author # print("loadMain author={}".format(author)) return self.getUserInfo() def getUserInfo(self): loginurl = self.baseurl + "/services/organization/api/current/dept/info" self.headers['Referer'] = self.baseurl response = self.session.get(loginurl, headers=self.headers) response.encoding = 'utf-8' return self.login() def login(self): loginurl = self.baseurl + "/services/organization/api/ourmUser/login" self.headers['Referer'] = self.baseurl response = self.session.get(loginurl, headers=self.headers) response.encoding = 'utf-8' return self.getOrgInfo() def getOrgInfo(self): loginurl = self.baseurl + "/services/organization/api/ourmUser/list" self.headers['Referer'] = self.baseurl response = self.session.get(loginurl, headers=self.headers) response.encoding = 'utf-8' params = [ # {"betweenMap": {}, "dto": {"status": "DISTRIBUTING"}, "extMap": {}, "searchMap": {}}, {"dto": {"status": "ACCEPTED"}, "pageIndex": 1, "pageSize": 50}, {"dto": {"status": "RESERVATION"}, "pageIndex": 1, "pageSize": 50}] orderlist = [] for param in params: orders = self.loadOrders(param) if orders and len(orders) > 0: orderlist += orders print("orderlist count={} orderlist={}".format(len(orderlist), orderlist)) try: data = {"data": json.dumps(orderlist)} requests.post(self.bjdomain + "/Api/Climborder/addorder", data=data) except Exception as e: print("addorder failed:", e) return self.datafail return self.datasuccess def loadOrders(self, param=None): orderurl = self.baseurl + "/services/distributeproce/api/repair/acl/_search/page" # RESERVATION 待确认 ACCEPTED 待预约 DISTRIBUTING 待接单 VISIT 待完工 # 维修任务 # {"betweenMap":{},"dto":{"type":"REPAIR_ACL_OWN_NOT"},"searchMap":{"status":{"opt":"IN","value":"SUBMIT,ACCEPTED,RESERVATION,VISIT"}},"pageIndex": 1,"pageSize":10} # params = {"betweenMap": {}, "dto": {"status": "DISTRIBUTING"}, "extMap": {}, "searchMap": {}, "pageIndex": 1, "pageSize": 50} # params = {"dto": {"status": "ACCEPTED"}, "pageIndex": 1, "pageSize": 50} self.headers['Request-Source'] = 'PC' self.headers['Sec-Fetch-Dest'] = 'empty' response = self.session.post(orderurl, data=json.dumps(param), headers=self.headers) response.encoding = 'utf-8' datas = json.loads(response.text) # print("====================================loadOrders") # print(params) # print(response.text) if datas['status'] == 200: try: return self.parseOrders(datas) except Exception as e: print("addorder failed:", e) return [] def parseOrders(self, datas): total_num = datas['data']['totalElements'] order_list = [] for order_key in datas['data']['content']: # repairSubOrderNum :"PD2020042801002-01" repairNum :"PD2020042801002" reportNum :BDX2020042800717 repairtime = order_key['reservationDate'] if not order_key['reservationFirstTime'] else order_key[ 'reservationFirstTime'] if not order_key['reservationSuccessTime'] else order_key[ 'reservationSuccessTime'] if repairtime: repairtime = repairtime.replace("T", ' ') orderno = order_key['repairSubOrderNum'] if order_key['repairSubOrderNum'] else order_key['reportNum'] order_info = {'factorynumber': orderno, 'ordername': order_key['serviceTypeName'], 'username': order_key['purchaserName'], 'mobile': order_key['purchaserPhone'], 'orderstatus': order_key['statusName'], 'originname': '康佳系统', 'mastername': order_key['repairAclName'], 'machinetype': order_key['seriesName'], 'machinebrand': '康佳', 'sn': '', 'companyid': self.factoryid, 'adminid': self.adminid, 'address': str(order_key['purchaserReportAddress']), 'province': order_key['provinceName'], 'city': order_key['cityName'], 'county': order_key['regionName'], 'town': order_key['countyName'], 'ordertime': order_key['createdDate'], 'repairtime': repairtime, 'note': str(order_key['brandName']) + str(order_key['serviceNatureName']), 'description': order_key['userFaultDesc'], } order_list.append(order_info) return order_list if __name__ == '__main__': util = ConkaUtil('K608069', 'Crm@20200401', adminid='15870', factoryid='1') # util = ConkaUtil('K608475', 'Kuser6646!', adminid='20699', factoryid='1') # util = ConkaUtil('K608069', 'Crm@20200401', adminid='24', factoryid='1') print(util.loadMain())
{"/SuningUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/huadi_zb.py": ["/Util.py"], "/TCSMCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/CDKCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/GreeUtil.py": ["/Util.py"], "/MideaUtil.py": ["/BaseUtil.py"], "/BaseUtil.py": ["/Util.py", "/cookie_test.py"], "/master.py": ["/searchutil.py"], "/login.py": ["/CDKUtil.py"], "/MideaCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/test/http2.py": ["/BaseUtil.py"], "/MIUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/JDUtil.py": ["/BaseUtil.py"], "/cookie_test.py": ["/aesgcm.py"]}
3,885
chengyan1984/cdk-gui
refs/heads/master
/SuningUtil.py
import json import re import time from datetime import date, timedelta from urllib import parse from urllib.parse import urlencode, urlparse import requests from BaseUtil import BaseUtil from cookie_test import fetch_chrome_cookie class SuningUtil(BaseUtil): def __init__(self, username, passwd, adminid='24', factoryid='4', baseurl='http://ases.suning.com', bjdomain='http://yxgtest.bangjia.me'): super(SuningUtil, self).__init__(username, passwd, adminid, factoryid, baseurl, bjdomain) self.headers['Accept'] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng," \ "*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" # self.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8' self.headers['Accept-Encoding'] = 'gzip, deflate' self.headers['Accept-Language'] = 'zh-CN,zh;q=0.9' self.cookie = fetch_chrome_cookie([ {"domain": "ases.suning.com"}, {"domain": ".ases.suning.com"}, {"domain": ".suning.com"}, {"domain": "tianyan.suning.com"}, ], isExact=True) self.cookies = BaseUtil.getCookies(self.cookie) self.headers['Cookie'] = self.cookie # print(self.cookie) self.userinfo = None def loadBI(self, param=None): # print("===================loadBI") loginurl = self.baseurl + "/ases-web/main/homeServiceOrders/biSmgzbb.action" header = self.headers.copy() del header['Content-Type'] del header['Origin'] loginRes = self.session.get(loginurl, headers=header) url = loginRes.url print(url) return url if "guId" in url else None def loadMenu(self, param=None): # print("===================loadMenu") loginurl = self.baseurl + "/ases-web/main/menu/queryMenu.action?pId=FUN_18_02" self.headers['Accept'] = 'application/json, text/plain, */*' self.headers['Referer'] = self.baseurl + '/ases-web/index.html' menuRes = self.session.get(loginurl, headers=self.headers) # print(menuRes.headers) # FUN_18_02_33 BI FUN_18_02_04:改派工人管理 # print(menuRes.text) def getUserinfo(self, param=None): # self.loadMenu() print("===================getUserinfo") loginurl = self.baseurl + "/ases-web/main/user/userInfo.action" self.headers['Accept'] = 'application/json, text/plain, */*' self.headers['Referer'] = self.baseurl + '/ases-web/index.html' print("headers=", self.headers) userRes = self.session.get(loginurl, headers=self.headers) print("userRes=", userRes.text) userinfo = self.getjson(userRes) print(userinfo) if userinfo and userinfo['result'] and userinfo['data']: wd = userinfo['data']['wd'] supplierCode = userinfo['data']['supplierCode'] userId = userinfo['data']['userId'] companyCode = userinfo['data']['companyCode'][0] result = {"wd": wd, "supplierCode": supplierCode, "userId": userId, "companyCode": companyCode} return result return None def loadOrders(self, param=None): # print("=================================loadOrders") if not self.userinfo: self.userinfo = self.getUserinfo() if not self.userinfo: return self.datafail biurl = self.loadBI() if not biurl: return self.datafail parsed_uri = urlparse(biurl) tianyanbase = parsed_uri.scheme + "://" + parsed_uri.netloc url = tianyanbase + "/lbi-web-in/ww/visittrack/queryGrid.action" header = {'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': self.agent, 'Upgrade-Insecure-Requests': '1', 'Host': parsed_uri.netloc, 'Origin': tianyanbase, 'Cookie': self.cookie, 'Accept-Encoding': 'gzip, deflate', 'Connection': 'keep-alive', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Accept': 'text/html, */*; q=0.01'} bires = self.session.get(biurl, headers=header) # print("bires=", bires.text) # print("bires header=", bires.headers) cookies = self.cookies.copy() for c in bires.cookies: cookies[c.name] = c.value # print(c.name, c.value) header['Referer'] = biurl header['Cookie'] = self.initCookie(cookies) orders = list(self.searchBI(url, header, 1)) print("loadOrders result count=", len(orders)) try: data = {"data": json.dumps(orders)} # print(data) requests.post(self.bjdomain + "/Api/Climborder/addorder", data=data) self.loadGaipaiOrder() except: return self.dataverify return self.datasuccess def initCookie(self, cookies=None): if not cookies: return "" result = "" for cookie in cookies: result += cookie + "=" + cookies[cookie] + "; " return result[:-2] def searchBI(self, url, header, page=1, totalcount=100): params = {"wd": self.userinfo['wd'][0], "companyCode": self.userinfo['companyCode'], "reservationStartDate": (date.today() - timedelta(days=1)).strftime("%Y%m%d"), "reservationEndDate": (date.today() + timedelta(days=1)).strftime("%Y%m%d"), "sapOrderType": "ZS01,ZS02,ZS03,ZS04,ZS06,ZS11,ZS12,ZS24", "page": str(page), "pageSize": "10" } # print("header['Cookie']=", header['Cookie']) biresult = self.session.post(url, headers=header, data=params) # print("url=", url, "biresult=", biresult.text) soup = self.getsoup(biresult) totalRe = re.findall(re.compile(r"(\d+)", re.S), soup.find("span", {"class": "total"}).text.strip()) if totalRe and len(totalRe) > 0: totalcount = totalRe[0] try: pageCount = int(soup.find("input", {"id": "pageCount"})['value']) except: pageCount = 0 resulttable = soup.find("table", {"class": "webtable"}) isall = page + 1 > pageCount print("totalcount=", totalcount, "pageCount=", pageCount, "page=", page, "isall=", isall) if resulttable: yield from self.parseOrders2(resulttable.find_all("tr"), header['Referer']) if not isall: yield from self.searchBI(url, header, page + 1, totalcount) def parseOrders2(self, tr_list, biurl): for tr in tr_list: if tr.has_attr('class'): continue order = self.parseOrder(tr) if order: yield self.orderdetail(order, biurl) def parseOrder(self, tr): tablecolumns = tr.find_all("td") try: orderno_td = tablecolumns[0] addr = tablecolumns[14].text.strip().split(";") # 0;安徽省;六安市;**** orderitem = orderno_td.find("a") if orderitem: # 这个是元素的点击事件id,下一个页面需要用到 data = { "oid": re.findall(re.compile(r"[(]'(.*?)'[)]", re.S), orderitem["onclick"])[0], 'factorynumber': self.finda(orderno_td), 'originname': tablecolumns[16].text.strip(), 'username': tablecolumns[13].text.strip(), 'mobile': tablecolumns[15].text.strip(), 'ordername': tablecolumns[2].text.strip().replace("服务订单", ""), 'ordertime': tablecolumns[6].text.strip(), 'mastername': tablecolumns[23].text.strip(), 'province': addr[1] if len(addr) > 1 else "", 'city': addr[2] if len(addr) > 2 else "", 'companyid': self.factoryid, 'machinebrand': tablecolumns[9].text.strip().split("(")[0], 'machinetype': tablecolumns[8].text.strip(), 'version': tablecolumns[7].text.strip(), # 'machinebrand': re.findall(re.compile(r"(.*?)[(].*?[)]", re.S), tablecolumns[9].text.strip())[0], 'orderstatus': tablecolumns[4].text.strip(), 'adminid': self.adminid} print("parseorder data=", data) return data # if self.isNew(data, self.bjdomain, self.adminid) else None except Exception as e: print("parseorder exception", e) return None def orderdetail(self, data, biurl): """获取到的是aes加密后的数据,暂未找到破解方法""" # url = self.baseurl + "/ases-web/main/external/bi/changeShow.action?orderId=" + data['oid'] # header = self.headers.copy() # header['Referer'] = biurl # detailRes = self.session.get(url, headers=header) # print("detailRes=", detailRes.text) # print("detail url=", detailRes.url) return data def loadGaipaiOrder(self): # 开始加载工单 self.headers['Accept'] = "application/json, text/plain, */*" self.headers['Content-Type'] = 'application/json' url = self.baseurl + "/ases-web/main/ui/dispatchWorker/queryList.action" params = {"wds": self.userinfo['wd'], "companyCode": self.userinfo['companyCode'], "srvTimeStart": (date.today() - timedelta(days=3)).strftime("%Y-%m-%d"), "srvTimeEnd": (date.today() + timedelta(days=3)).strftime("%Y-%m-%d"), "page": "1", "pageSize": "100" } url = url + "?" + str(parse.urlencode(params)) orderRes = self.session.get(url, headers=self.headers) gaipaiOrder = self.parseOrders(orderRes) """以下获取的es数据也为加密后的数据""" # print("orderRes.text=", orderRes.text) # esurl = self.baseurl + "/ases-web/main/ui/smOrder/queryListFromES.action" # self.headers['Content-Type'] = 'application/x-www-form-urlencoded' # self.headers['Accept-Encoding'] = 'gzip, deflate' # self.headers['Accept'] = 'application/json, text/plain, */*' # params = {"wd": self.userinfo['wd'][0], "companyCode": self.userinfo['companyCode'], # "srvSaleCountStart": (date.today() - timedelta(days=3)).strftime("%Y-%m-%d"), # "srvSaleCountEnd": (date.today() + timedelta(days=3)).strftime("%Y-%m-%d"), # "createTimeStart": "", "createTimeEnd": "", "finishTimeStart": "", "finishTimeEnd": "", # "orderId": "", "cmmdtyCtgry": "", "cityCodes": "", "mobPhoneNum": "", # "page": "1", "pageSize": "100" # } # print("esorder params=", params) # orderRes = self.session.post(esurl, headers=self.headers, data=params) # print("esorder orderRes.text=", orderRes.text) # ESOrder = self.parseOrders(orderRes) ESOrder = [] try: data = {"data": json.dumps(gaipaiOrder + ESOrder)} # print(data) requests.post(self.bjdomain + "/Api/Climborder/addorder", data=data) except: return self.dataverify return self.datasuccess def parseOrders(self, orderRes): datas = self.getjson(orderRes) orders = [] if datas and 'result' in datas and datas['result'] and datas['data']: items = datas['data']['datas'] else: return orders for item in items: orders.append({ 'factorynumber': item['orderId'], 'ordername': item['operateItemDec'], 'username': item['consignee'], 'mobile': item['mobPhoneNum'], 'orderstatus': "改派工人", 'originname': "苏宁", # 'machinetype': item['PROD_NAME'], 'machinebrand': item['BRAND_NAME'], 'sn': item['cmmdtyCode'], 'version': item['cmmdtyName'] if 'cmmdtyName' in item else '', 'repairtime': item['srvTime'] if 'srvTime' in item else '', 'mastername': item['zyry1BpName'] if 'zyry1BpName' in item else '', 'note': item['srvMemo'] if 'srvMemo' in item else '', 'companyid': self.factoryid, 'adminid': self.adminid, 'address': str(item['srvAddress']).replace(";", "").strip(), # 'province': item['provinceName'], 'city': item['cityName'], # 'county': item['regionName'], 'town': item['countyName'], 'description': str(item['orderType']) + self.parseOrderType(item['orderType']), }) return orders def parseOrderType(self, ordertype): if ordertype == "ZS01": return "新机安装" elif ordertype == "ZS02": return "辅助安装" elif ordertype == "ZS03": return "移机" elif ordertype == "ZS04": return "退换货拆装" elif ordertype == "ZS06": return "上门维修" elif ordertype == "ZS09": return "用户送修检测" elif ordertype == "ZS10": return "用户送修维修" elif ordertype == "ZS11": return "上门鉴定" elif ordertype == "ZS12": return "清洗/保养" elif ordertype == "ZS24": return "家电回收" elif ordertype == "ZS30": return "家装" else: return "安装" if __name__ == '__main__': util = SuningUtil('W850018433', 'sn789456', adminid='24', factoryid='99') print(util.loadOrders()) # print(util.loadBI())
{"/SuningUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/huadi_zb.py": ["/Util.py"], "/TCSMCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/CDKCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/GreeUtil.py": ["/Util.py"], "/MideaUtil.py": ["/BaseUtil.py"], "/BaseUtil.py": ["/Util.py", "/cookie_test.py"], "/master.py": ["/searchutil.py"], "/login.py": ["/CDKUtil.py"], "/MideaCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/test/http2.py": ["/BaseUtil.py"], "/MIUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/JDUtil.py": ["/BaseUtil.py"], "/cookie_test.py": ["/aesgcm.py"]}
3,886
chengyan1984/cdk-gui
refs/heads/master
/huadi_zb.py
# -*- coding: utf-8 -*- import requests import json from bs4 import BeautifulSoup import re from datetime import date, timedelta, datetime from Util import Util class HDScrap(Util): def __init__(self, username='01007544', pwd='160324', baseurl="http://cc.vatti.com.cn:8180", adminid='3', bjdomain='http://yxgtest.bangjia.me', companyid='9'): self.session = requests.Session() self.username = username self.passwd = pwd self.baseurl = baseurl self.codeFaultTimes = 0 self.loginFaultTimes = 0 self.adminid = adminid self.bjdomain = bjdomain self.datasuccess = {'code': 1, 'msg': '抓单成功', 'element': ''} self.datafail = {'code': 0, 'msg': '登录失败,请检查账号密码是否正确'} self.isSucess = False self.companyid = companyid self.mainurl = None self.headers = {'Content-type': 'text/html', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,pt;q=0.6', 'Connection': 'keep-alive', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,' '*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Host': "cc.vatti.com.cn:8180", 'Origin': baseurl, # 'User-Agent': agent, 'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/79.0.3945.88 Safari/537.36"} def get_lsdata(self, element): data = element["lsdata"] data = data.replace(r"true", '1') data = data.replace(r"false", '0') return eval(data)[2] def get_value(self, element): return element["value"] def loginHd(self): loginurl = self.baseurl + '/sap/bc/bsp/sap/crm_ui_start/default.htm?sap-client=800&sap-language=ZH' print("url=" + loginurl + ",passwd=" + self.passwd) self.headers['Referer'] = loginurl loginRes = self.session.get(loginurl, headers=self.headers) loginRes.encoding = 'utf-8' bsObj = BeautifulSoup(loginRes.text, features="lxml") # print("=========================") processname = self.get_value(bsObj.find("input", {"name": "sap-system-login"})) sap_client = self.get_value(bsObj.find("input", {"id": "sap-client"})) loginxsrf = bsObj.find("input", {"name": "sap-login-XSRF"})["value"] params = {"FOCUS_ID": self.get_value(bsObj.find("input", {"id": "FOCUS_ID"})), "sap-system-login-oninputprocessing": processname, "sap-system-login": processname, "sap-login-XSRF": loginxsrf, "sysid": self.get_lsdata(bsObj.find("input", {"id": "sysid"})), "sap-client": sap_client, "sap-user": self.username, "sap-password": self.passwd, "SAPEVENTQUEUE": "Form_Submit~E002Id~E004SL__FORM~E003~E002ClientAction~E004submit~E005ActionUrl~E004" "~E005ResponseData~E004full~E005PrepareScript~E004~E003~E002~E003", "sap-language": self.get_value(bsObj.find("input", {"id": "sap-language"})), "sap-language-dropdown": self.get_value(bsObj.find("input", {"id": "sap-language-dropdown"}))} self.headers['Content-type'] = "application/x-www-form-urlencoded" checkRes = self.session.post(loginurl, data=params, headers=self.headers) self.selectrole() return self.checkstatus(checkRes) def checkstatus(self, response, callback=None): bsObj = self.getsoup(response) nextbtn = bsObj.find_all("a", {"id": "SESSION_QUERY_CONTINUE_BUTTON"}) logonbtn = bsObj.find_all("a", {"id": "LOGON_BUTTON"}) # 如果账号密码错误 或者其他问题,直接返回 if response.status_code != 200: return self.datafail # 如果有其他账户在登陆,点击继续 elif nextbtn: return self.continuelogon() elif logonbtn: return self.datafail if callback: return callback(bsObj) return self.datasuccess def continuelogon(self, callback=None): """ 点击继续,踢掉其他用户继续当前会话 """ print("有其他账户登陆,点击继续") params = {"FOCUS_ID": "SESSION_QUERY_CONTINUE_BUTTON", "sap-system-login-oninputprocessing": "onSessionQuery", "sap-system-login": "onSessionQuery", "sap-client": '800', "SAPEVENTQUEUE": "Form_Submit~E002Id~E004SL__FORM~E003~E002ClientAction~E004submit~E005ActionUrl~E004" "~E005ResponseData~E004full~E005PrepareScript~E004~E003~E002~E003", "sap-language": 'ZH', "delete-session-cb": 'X', "delete_session": 'X' } self.headers['Content-type'] = "application/x-www-form-urlencoded" url = self.baseurl + '/sap/bc/bsp/sap/crm_ui_start/default.htm' checkRes = self.session.post(url, data=params, headers=self.headers) # print(checkRes.status_code) if checkRes.status_code != 200: return self.datafail result = self.selectrole() if callback: return callback() return result def selectrole(self): # print('=========================选择角色') url = self.baseurl + "/sap/bc/bsp/sap/crm_ui_frame/main.htm?sap-client=800&sap-language=ZH&sap-domainRelax" \ "=min&saprole=ZIC_AGENT_08&sapouid=50000265&sapoutype=S" roleRes = self.session.get(url, headers=self.headers) if roleRes.status_code != 200: return self.datafail return self.datasuccess def getsoup(self, response): # print(response.status_code) response.encoding = 'utf-8' return BeautifulSoup(response.text, features="lxml") def transfer_order(self, statuscode=None): # print('=========================loadFrame1 加载左边的动作栏') url = self.mainurl if not url or len(url) <= 1: url = self.baseurl + "/sap/bc/bsp/sap/crm_ui_frame/BSPWDApplication.do?sap-client=800&sap-language=ZH&sap" \ "-domainrelax=min&saprole=ZIC_AGENT_08&sapouid=50000265&sapoutype=S" self.headers['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' del self.headers['Content-type'] actionRes = self.session.get(url, headers=self.headers) # print(actionRes.text) result = self.checkstatus(actionRes) if result['code'] == 1: try: bsObj = self.getsoup(actionRes) if not bsObj: return self.datafail sercureid = self.get_value(bsObj.find("input", {"id": "wcf-secure-id"})) cb_flash = self.get_value(bsObj.find("input", {"id": "callbackFlashIslands"})) cb_light = self.get_value(bsObj.find("input", {"id": "callbackSilverlightIslands"})) data = {"data": json.dumps(self.loadallsearch(sercureid, cb_flash, cb_light, statuscode))} if statuscode: data['vatti_type'] = 1 # print("transfer_order:", data) result = requests.post(self.bjdomain + "/Api/Climborder/addorder", data=data) # print(result) except Exception as e: print("transfer_order exception", e) return self.datafail return self.datasuccess else: return self.datafail def loadsearch(self, sercureid, cb_flash, cb_light): # print('=========================loadsearch 加载工单查询初始页面') params = {"callbackFlashIslands": cb_flash, "callbackSilverlightIslands": cb_light, "htmlbevt_frm": "myFormId", "htmlbevt_cnt": "0", "onInputProcessing": "htmlb", "htmlbevt_ty": "thtmlb:link:click:0", "htmlbevt_id": "ZSRV-02-SR", "htmlbevt_oid": "C6_W29_V30_ZSRV-01-SR", "thtmlbKeyboardFocusId": "C6_W29_V30_ZSRV-01-SR", "sap-ajaxtarget": "C1_W1_V2_C6_W29_V30_MainNavigationLinks.do", "sap-ajax_dh_mode": "AUTO", "wcf-secure-id": sercureid, "PREFIX_ID": "C9_W36_V37_", "LTX_PREFIX_ID": "C1_W1_V2_", "sap-ajax_request": "X", "C4_W23_V24_V25_tv1_multiParameter": "0////0////0////0", "C8_W34_V35_RecentObjects_isExpanded": "yes", "C4_W23_V24_V25_tv1_isCellerator": "TRUE", "C4_W23_V24_V25_tv1_isNavModeActivated": "TRUE", "C4_W23_V24_V25_tv1_filterApplied": "FALSE", "C4_W23_V24_V25_tv1_editMode": "NONE", "C4_W23_V24_V25_tv1_firstTimeRendering": "NO", "C9_W36_V37_POLLFREE_ALERTS": "{&#34;Alerts&#34;:[]}", "C4_W23_V24_V25_tv1_configHash": "827DEA574484325768AF0E54A8EB7CBF8083ED01", "C3_W18_V19_V21_searchcustomer_struct.reltyp": "BUR001", "C4_W23_V24_V25_tv1_bindingString": "//CUSTOMERS/Table", "C13_W47_V48_SearchMenuAnchor1": "UP" } sap = re.findall(re.compile(r'[(](.*?)[)]', re.S), params['callbackFlashIslands'])[0] url = self.baseurl + "/sap(%s)/bc/bsp/sap/crm_ui_frame/BSPWDApplication.do" % sap print("loadsearch url={}".format(url)) self.mainurl = url self.headers['Content-type'] = "application/x-www-form-urlencoded" self.headers['Referer'] = url # 该参数代表了是否异步加载,如果加了这个选项,会只能接受到建议的网页,导致解析出错,浪费2天时间 # self.headers['X-Requested-With'] = "XMLHttpRequest" self.headers['Accept'] = "*/*" roleRes = self.session.post(url, data=params, headers=self.headers) # print(roleRes.text) return self.getsoup(roleRes), params def loadallsearch(self, sercureid, cb_flash, cb_light, statuscode=None): soup, params = self.loadsearch(sercureid, cb_flash, cb_light) confighash = str(soup.find("input", {"id": "C17_W61_V62_V64_ResultTable_configHash"})["value"]) order = list(self.search(confighash, params, 0, statuscode=statuscode)) return order def search(self, confighash, _params, page, totalcount=100, pagecount=50, statuscode=None): # print('=========================loadsearch 搜索', '增值工单' if not statuscode else '安装工单') target = "C1_W1_V2_C1_W1_V2_V3_C17_W61_V62_SearchViewSet.do" if page == 0 else "C1_W1_V2_C1_W1_V2_V3_C17_W61_V62_C17_W61_V62_V64_advancedsrl.do" oid = "C17_W61_V62_Searchbtn" if page == 0 else "C17_W61_V62_V64_ResultTable" focusid = "C17_W61_V62_Searchbtn" if page == 0 else "C17_W61_V62_V64_ResultTable_pag_pg-%d" % page params = { "callbackFlashIslands": _params['callbackFlashIslands'], "callbackSilverlightIslands": _params['callbackSilverlightIslands'], "htmlbevt_frm": "myFormId", "htmlbevt_cnt": "0" if page == 0 else "1", "onInputProcessing": "htmlb", "htmlbevt_ty": "htmlb:button:click:0" if page == 0 else "thtmlb:tableView:navigate:null", "htmlbevt_id": "SEARCH_BTN" if page == 0 else "tvNavigator", "sap-ajax_dh_mode": "AUTO", "wcf-secure-id": _params['wcf-secure-id'], "PREFIX_ID": "C9_W36_V37_", "LTX_PREFIX_ID": "C1_W1_V2_", "sap-ajax_request": "X", "crmFrwScrollXPos": "0", "crmFrwScrollYPos": "267", "crmFrwOldScrollXPos": "0", "crmFrwOldScrollYPos": "267", "thtmlbScrollAreaWidth": "0", "thtmlbScrollAreaHeight": "0", "C13_W47_V48_SearchMenuAnchor1": "UP", 'htmlbevt_oid': oid, 'thtmlbKeyboardFocusId': focusid, 'sap-ajaxtarget': target, 'currentDate': datetime.now().year, 'C17_W61_V62_V64_ResultTable_configHash': confighash, 'C17_W61_V62_V64_ResultTable_multiParameter': "0////0////0////0", 'C17_W61_V62_V64_ResultTable_bindingString': "//BTQRSrvOrd/Table", 'C17_W61_V62_V64_ResultTable_sortValue': 'CREATED_AT#:#desc#!#', 'C17_W61_V62_V63_btqsrvord_max_hits': "9" if statuscode else "9", # 一次查询最大多少条 'C17_W61_V62_thtmlbShowSearchFields': "true", 'C17_W61_V62_V64_ResultTable_isNavModeActivated': "TRUE", 'C17_W61_V62_V64_ResultTable_filterApplied': "FALSE", 'C17_W61_V62_V64_ResultTable_isCellerator': "TRUE", 'C17_W61_V62_V64_ResultTable_editMode': "NONE", 'C17_W61_V62_V64_ResultTable_visibleFirstRow': str(1 + page * 10), "C17_W61_V62_V63_btqsrvord_parameters[1].FIELD": "POSTING_DATE", "C17_W61_V62_V63_btqsrvord_parameters[1].OPERATOR": "GT" if not statuscode else "EQ", "C17_W61_V62_V63_btqsrvord_parameters[1].VALUE1": (date.today() - timedelta(days=1)).strftime("%Y.%m.%d"), "C17_W61_V62_V63_btqsrvord_parameters[1].VALUE2": "", "C17_W61_V62_V63_btqsrvord_parameters[2].FIELD": "ZZFLD000057", "C17_W61_V62_V63_btqsrvord_parameters[2].OPERATOR": "EQ", "C17_W61_V62_V63_btqsrvord_parameters[2].VALUE1": "", "C17_W61_V62_V63_btqsrvord_parameters[2].VALUE2": "", "C17_W61_V62_V63_btqsrvord_parameters[3].FIELD": "ZZFLD000063", "C17_W61_V62_V63_btqsrvord_parameters[3].OPERATOR": "EQ", "C17_W61_V62_V63_btqsrvord_parameters[3].VALUE1": "", "C17_W61_V62_V63_btqsrvord_parameters[3].VALUE2": "", "C17_W61_V62_V63_btqsrvord_parameters[4].FIELD": "ZZFLD00005P", "C17_W61_V62_V63_btqsrvord_parameters[4].OPERATOR": "EQ", "C17_W61_V62_V63_btqsrvord_parameters[4].VALUE1": "01" if not statuscode else "", # 工单来源是HD-华帝 "C17_W61_V62_V63_btqsrvord_parameters[4].VALUE2": "", "C17_W61_V62_V63_btqsrvord_parameters[5].FIELD": "OBJECT_ID", "C17_W61_V62_V63_btqsrvord_parameters[5].OPERATOR": "EQ", "C17_W61_V62_V63_btqsrvord_parameters[5].VALUE1": "", "C17_W61_V62_V63_btqsrvord_parameters[5].VALUE2": "", "C17_W61_V62_V63_btqsrvord_parameters[6].FIELD": "PROCESS_TYPE", "C17_W61_V62_V63_btqsrvord_parameters[6].OPERATOR": "EQ", "C17_W61_V62_V63_btqsrvord_parameters[6].VALUE1": "ZIC6" if not statuscode else "ZIC3", # 工单类型为 增值服务单 "C17_W61_V62_V63_btqsrvord_parameters[6].VALUE2": "", "C17_W61_V62_V63_btqsrvord_parameters[7].FIELD": "ZZFLD00003J", "C17_W61_V62_V63_btqsrvord_parameters[7].OPERATOR": "EQ", "C17_W61_V62_V63_btqsrvord_parameters[7].VALUE1": "", "C17_W61_V62_V63_btqsrvord_parameters[7].VALUE2": "", # "C17_W61_V62_V63_btqsrvord_parameters[8].FIELD": "STATUS_COMMON", # "C17_W61_V62_V63_btqsrvord_parameters[8].OPERATOR": "EQ", # "C17_W61_V62_V63_btqsrvord_parameters[8].VALUE1": "M0002ZSIC0002", # 状态为工单提交 # "C17_W61_V62_V63_btqsrvord_parameters[8].VALUE2": "", # "C17_W61_V62_V63_btqsrvord_parameters[9].FIELD": "ZZFLD000062", # "C17_W61_V62_V63_btqsrvord_parameters[9].OPERATOR": "EQ", # "C17_W61_V62_V63_btqsrvord_parameters[9].VALUE1": "", # "C17_W61_V62_V63_btqsrvord_parameters[9].VALUE2": "", 'C17_W61_V62_V64_ResultTable_firstTimeRendering': "NO", "C9_W36_V37_POLLFREE_ALERTS": "{&#34;Alerts&#34;:[]}", "C17_W61_V62_V64_ResultTable_rowCount": "0" if page == 0 else str(totalcount) } # if statuscode: # params["C17_W61_V62_V63_btqsrvord_parameters[8].FIELD"] = "STATUS_COMMON" # params["C17_W61_V62_V63_btqsrvord_parameters[8].OPERATOR"] = "EQ" # params["C17_W61_V62_V63_btqsrvord_parameters[8].VALUE1"] = statuscode # params["C17_W61_V62_V63_btqsrvord_parameters[8].VALUE2"] = "" if page != 0: params['htmlbevt_par1'] = "page:%d,%d,%d,%d,P" % (page + 1, 1 + page * pagecount, pagecount, totalcount) sap = re.findall(re.compile(r'[(](.*?)[)]', re.S), params['callbackFlashIslands'])[0] url = self.baseurl + "/sap(%s)/bc/bsp/sap/crm_ui_frame/BSPWDApplication.do" % sap self.headers['Content-type'] = "application/x-www-form-urlencoded" self.headers['Referer'] = url print("page={},totalcount={},url={},headers={}".format(page, totalcount, url, self.headers)) roleRes = self.session.post(url, data=params, headers=self.headers) bsObj = self.getsoup(roleRes) # if statuscode: # print("search result={}".format(roleRes.text)) resulttable = bsObj.find("table", {"id": "C17_W61_V62_V64_ResultTable_TableHeader"}).find("tbody") totalcount = int(bsObj.find("input", {"id": "C17_W61_V62_V64_ResultTable_rowCount"})["value"]) isall = (page + 1) * pagecount >= totalcount print("totalcount=%d" % totalcount + ",page=%d" % page + ",isallloaded=%d" % isall) if resulttable: yield from self.parseorderlist(resulttable.find_all("tr"), url, params, statuscode) if not isall: yield from self.search(confighash, _params, page + 1, totalcount, pagecount, statuscode) def parseorderlist(self, trlist, url, params, statuscode): for tr in trlist: tablecolumns = tr.find_all("td") if tr and len(tablecolumns) > 2: data = self.parseorder(tablecolumns, statuscode) if data: yield from self.orderdetail(data, url, params, statuscode) def parseorder(self, tablecolumns, statuscode=None): try: orderno_td = tablecolumns[1] name_td = tablecolumns[3] data = {} orderitem = orderno_td.find("a") nameaddress = self.finda(name_td).split(" / ") if orderitem and orderitem.has_attr('id'): data['oid'] = orderitem["id"] # 这个是上一个列表中的工单号元素id,下一个页面需要用到 data['pid'] = name_td.find("a")['id'] # 这个是上一个列表中的用户名元素id,下一个页面需要用到 data['factorynumber'] = self.finda(orderno_td) data['username'] = nameaddress[0] data['originname'] = self.findspan(tablecolumns[4]) data['ordertime'] = self.findspan(tablecolumns[7]).replace(".", '-') data['companyid'] = self.companyid data['machinebrand'] = "华帝" data['orderstatus'] = "工单提交" data['adminid'] = self.adminid if len(nameaddress) > 1 and "-" in nameaddress[1]: address = nameaddress[1].split("-") if len(address) > 1: data['city'] = address[0] data['county'] = address[1] # print("parseorder data=") # print(data) if data['username']: data['username'] = data['username'].split(" ")[0] return data if not statuscode or self.isNew(data, self.bjdomain, self.adminid) else None except Exception as e: print("parseorder exception", e) return None def orderdetail(self, data, url, params, statuscode): # print('=========================orderdetail 获取工单详情') oid = data['oid'] params['htmlbevt_ty'] = "thtmlb:link:click:0" params['htmlbevt_oid'] = oid params['thtmlbKeyboardFocusId'] = oid params['htmlbevt_id'] = "HEADEROV" params['htmlbevt_cnt'] = "0" params['currentDate'] = datetime.now().year params['sap-ajaxtarget'] = "C1_W1_V2_C1_W1_V2_V3_C17_W61_V62_C17_W61_V62_V64_advancedsrl.do" if 'htmlbevt_par1' in params: del params['htmlbevt_par1'] roleRes = self.session.post(url, data=params, headers=self.headers) bsObj = self.getsoup(roleRes) if statuscode: # print(roleRes.text) data['orderstatus'] = "服务完成" if statuscode == "M0010ZSIC0003" else "回访完成" data['machinetype'] = bsObj.find("span", {"id": "C19_W69_V72_V75_thtmlb_textView_28"}).text.strip() # 机器类型 data['buydate'] = bsObj.find("span", {"id": "C19_W69_V72_V75_btadminh_ext.zzfld00002y"}).text.strip() # 购买日期 data['ordername'] = "安装" data['sn'] = bsObj.find("span", {"id": "C19_W69_V72_V75_btadminh_ext.zzfld00001r"}).text.strip() # 条码 data['version'] = self.getTableRow(bsObj, "C23_W85_V86_V88_Table_TableHeader", lambda row: self.finda(row[3]) + "|") # 产品编号 拼接 data['machine_dsc'] = self.getTableRow(bsObj, "C23_W85_V86_V88_Table_TableHeader", lambda row: self.finda(row[6]) + "|") # 产品编号 拼接 data = self.getFinishTime(data, url, params) else: user_tr = bsObj.find("div", {"id": "C19_W69_V72_0003Content"}).find("tbody").find("tr") data['mobile'] = user_tr.find('span', id=re.compile('partner_no')).text.strip() data['address'] = user_tr.find('span', id=re.compile('address_short')).text.strip() data['repairtime'] = bsObj.find("span", {"id": "C19_W69_V72_V74_btadminh_ext.zzfld00003j"}).text.strip() # 预约时间 data['machinetype'] = bsObj.find("span", {"id": "C19_W69_V72_V74_thtmlb_textView_30"}).text.strip() # 机器类型 data['buydate'] = bsObj.find("span", {"id": "C19_W69_V72_V74_btadminh_ext.zzfld00002y"}).text.strip() # 购买日期 data['ordername'] = bsObj.find("span", {"id": "C19_W69_V72_V74_thtmlb_textView_20"}).text.strip() # 增值服务项 data['description'] = self.getTableRow(bsObj, "C23_W83_V84_V85_TextList_TableHeader" if not statuscode else "C24_W90_V91_V92_TextList_TableHeader", lambda row: self.findspan(row[0]) + ":" + self.finda(row[1]) + "\n") yield self.userdetail(data, url, params, statuscode) def getFinishTime(self, data, url, params): # print('=========================getFinishTime 获取工单完工时间') param = {"callbackFlashIslands": params["callbackFlashIslands"], "callbackSilverlightIslands": params["callbackSilverlightIslands"], "wcf-secure-id": params["wcf-secure-id"], "LTX_PREFIX_ID": params["LTX_PREFIX_ID"], "PREFIX_ID": 'C9_W36_V37_', "crmFrwScrollXPos": '0', "crmFrwOldScrollXPos": '0', "currentDate": params["currentDate"], 'htmlbevt_ty': "thtmlb:tableView:navigate:null", 'htmlbevt_oid': "C31_W114_V115_DatesTable", 'htmlbevt_frm': "myFormId", 'htmlbevt_id': "tvNavigator", 'htmlbevt_cnt': "1", 'htmlbevt_par1': "page:2,11,10,18,P", 'sap-ajaxtarget': "C1_W1_V2_C1_W1_V2_V3_C19_W69_V72_C31_W114_V115_Dates.do", 'sap-ajax_dh_mode': "AUTO", 'onInputProcessing': "htmlb", 'C13_W47_V48_SearchMenuAnchor1': "UP", 'C8_W34_V35_RecentObjects_isExpanded': "yes", 'C23_W85_V86_V88_Table_editMode': "NONE", 'C19_W69_V72_0001_displaymode': "X", 'C23_W85_V86_V87_itemobjecttype_itemobjecttype': "ALL", 'C23_W85_V86_V88_Table_isCellerator': "TRUE", 'C23_W85_V86_V88_Table_rowCount': "1", 'C23_W85_V86_V88_Table_visibleFirstRow': "1", 'C23_W85_V86_V88_Table_bindingString': "//BTAdminI/Table", 'C23_W85_V86_V88_Table_isNavModeActivated': "TRUE", 'C23_W85_V86_V88_Table_configHash': "9EEC78D4306657883F5C86BEFC0745B37DA819FE", 'C23_W85_V86_V88_Table_multiParameter': "0////0////0////0", 'C19_W69_V72_0002_displaymode': "X", 'C24_W90_V91_V92_TextList_rowCount': "3", 'C24_W90_V91_V92_TextList_visibleFirstRow': "1", 'C24_W90_V91_V92_TextList_bindingString': "//Text/Table", 'C24_W90_V91_V92_TextList_isNavModeActivated': "TRUE", 'C24_W90_V91_V92_TextList_configHash': "0E513D2C7268EC204F42B18C06AFE9CDEC0335E5", 'C24_W90_V91_V92_TextList_multiParameter': "0////0////0////0", 'C19_W69_V72_0003_displaymode': "X", 'C25_W94_V95_Table_isCellerator': "TRUE", 'C25_W94_V95_Table_rowCount': "0", 'C25_W94_V95_Table_visibleFirstRow': "1", 'C25_W94_V95_Table_bindingString': "//DocList/Table", 'C25_W94_V95_Table_isFrontendSelection': "TRUE", 'C25_W94_V95_Table_isNavModeActivated': "TRUE", 'C25_W94_V95_Table_configHash': "2B1898492BCC377ECF844081E0C8B91EEB805379", 'C25_W94_V95_Table_multiParameter': "0////0////0////0", 'C19_W69_V72_0004_displaymode': "X", 'C19_W69_V72_0006_displaymode': "X", 'C27_W103_V104_ConfCellTable_isCellerator': "TRUE", 'C27_W103_V104_ConfCellTable_rowCount': "0", 'C27_W103_V104_ConfCellTable_visibleFirstRow': "1", 'C27_W103_V104_ConfCellTable_bindingString': "//TranceList/Table", 'C27_W103_V104_ConfCellTable_isNavModeActivated': "TRUE", 'C27_W103_V104_ConfCellTable_configHash': "7D633AD0A8F7098E6A03D3F0BBA3020EB7F11686", 'C27_W103_V104_ConfCellTable_multiParameter': "0////0////0////0", 'C19_W69_V72_0007_displaymode': "X", 'C19_W69_V72_0008_displaymode': "X", 'C29_W108_V109_ConfCellTable_isCellerator': "TRUE", 'C29_W108_V109_ConfCellTable_rowCount': "0", 'C29_W108_V109_ConfCellTable_visibleFirstRow': "1", 'C29_W108_V109_ConfCellTable_bindingString': "//ZCall/Table", 'C29_W108_V109_ConfCellTable_isNavModeActivated': "TRUE", 'C29_W108_V109_ConfCellTable_configHash': "E24612518975848E7FAA1EF476EBF26F7D025301", 'C29_W108_V109_ConfCellTable_multiParameter': "0////0////0////0", 'C19_W69_V72_0009_displaymode': "X", 'C30_W110_V111_TABLE_rowCount': "0", 'C30_W110_V111_TABLE_visibleFirstRow': "1", 'C30_W110_V111_TABLE_bindingString': "//ZTAB00011F/Table", 'C30_W110_V111_TABLE_isFrontendSelection': "TRUE", 'C30_W110_V111_TABLE_isNavModeActivated': "TRUE", 'C30_W110_V111_TABLE_configHash': "47B16290F9622C8097E999109F42C028F547915D", 'C30_W110_V111_TABLE_multiParameter': "0////0////0////0", 'C19_W69_V72_0010_displaymode': "X", 'C31_W114_V115_DatesTable_isCellerator': "TRUE", 'C31_W114_V115_DatesTable_rowCount': "18", 'C31_W114_V115_DatesTable_visibleFirstRow': "11", 'C31_W114_V115_DatesTable_bindingString': "//BTDate/Table", 'C31_W114_V115_DatesTable_isNavModeActivated': "TRUE", 'C31_W114_V115_DatesTable_configHash': "F1047D2E37AE2DE80BA46A1E06588EDC4440CA8A", 'C31_W114_V115_DatesTable_multiParameter': "0////0////0////0", 'C19_W69_V72_0011_displaymode': "X", 'thtmlbOverviewControllerID': "C19_W69_V72", 'crmFrwScrollYPos': "891", 'crmFrwOldScrollYPos': "891", 'thtmlbKeyboardFocusId': "C31_W114_V115_DatesTable_pag_pg-1", 'sap-ajax_request': "X"} url = url + "?sap-client=800&sap-language=ZH&sap-domainrelax=min&saprole=ZIC_AGENT_08&sapouid=50000265&sapoutype=S" # print("self.headers=", self.headers, ",url=", url) userRes = self.session.post(url, data=param, headers=self.headers) # print("param=", param) # print("getFinishTime result:", userRes.text) bsObj = self.getsoup(userRes) try: data['repairtime'] = self.getTableRow(bsObj, "C31_W114_V115_DatesTable_TableHeader", lambda r: self.findspan(r[1]).replace(".", '-') + " " + self.findspan( r[2]), row_no=-4, truncate=False) # crm完工日期作为安装日期 except Exception as e: print("getFinishTime exception", e) return data def userdetail2(self, data, url, params): # print('=========================userdetail2 从工单详情进入 查看用户详情') data['pid'] = 'C24_W88_V89_btpartner_table[1].thtmlb_oca.EDIT' # 通过元素获取? oid = data['oid'] pid = data['pid'] del data['pid'] del data['oid'] param = params.copy() param['htmlbevt_ty'] = "thtmlb:image:click:null::CL_THTMLB_TABLE_VIEW::EDIT.1" param['htmlbevt_oid'] = pid param['thtmlbKeyboardFocusId'] = pid param['htmlbevt_id'] = "ONE_CLICK_ACTION" param['htmlbevt_cnt'] = "0" param['sap-ajaxtarget'] = "C1_W1_V2_C1_W1_V2_V3_C24_W84_V87_C29_W103_V104_Partner.do" param['C23_W85_V86_V88_Table_configHash'] = "9EEC78D4306657883F5C86BEFC0745B37DA819FE" param['C24_W90_V91_V92_TextList_configHash'] = "0E513D2C7268EC204F42B18C06AFE9CDEC0335E5" param['C24_W90_V91_V92_TextList_multiParameter'] = "0////0////0////0" param['C24_W90_V91_V92_TextList_bindingString'] = "//Text/Table" userRes = self.session.post(url, data=param, headers=self.headers) bsObj = self.getsoup(userRes) data['mobile'] = str(bsObj.find("input", {"id": "C30_W123_V124_commdata_telephonetel"})["value"]) data['province'] = str(bsObj.find("input", {"id": "C30_W119_V120_postaldata_region_text"})["value"]) data['city'] = str(bsObj.find("input", {"id": "C30_W119_V120_postaldata_city"})["value"]) data['county'] = str(bsObj.find("input", {"id": "C30_W119_V120_postaldata_district"})["value"]) data['address'] = str(bsObj.find("input", {"id": "C30_W119_V120_postaldata_street"})["value"]) # 用户详细地址 data = self.clearAddress(data) # print('=========================orderdetail2 最终数据') # print(data) self.back2order(pid, url, params) self.back2orderlist(oid, url, params) return data def filterstr(self, address, filterstr): if address and filterstr and filterstr in address and address.startswith(filterstr): return address.replace(filterstr, '', 1) else: return address def userdetail(self, data, url, params, statuscode): # print('=========================userdetail 从工单列表进入查看用户详情') oid = data['oid'] self.back2orderlist(oid, url, params) # 返回到工单列表 del data['oid'] pid = data['pid'] del data['pid'] params['htmlbevt_ty'] = "thtmlb:link:click:0" params['htmlbevt_oid'] = pid params['thtmlbKeyboardFocusId'] = pid params['htmlbevt_id'] = "SOLD_TO_PARTY" params['htmlbevt_cnt'] = "0" params['sap-ajaxtarget'] = "C1_W1_V2_C1_W1_V2_V3_C17_W61_V62_C17_W61_V62_V64_advancedsrl.do" params['C17_W61_V62_V64_ResultTable_configHash'] = "F698293684A5C954932EE6CB006466A1645E5EF5" userRes = self.session.post(url, data=params, headers=self.headers) bsObj = self.getsoup(userRes) # C30_W119_V120_postaldata_street data['mobile'] = bsObj.find('span', id=re.compile('.TELEPHONE')).text.strip() # 用户电话 data['city'] = bsObj.find('input', id=re.compile('.city'))["value"] # 用户城市 data['address'] = str(bsObj.find('input', id=re.compile('.street'))["value"]) # 用户详细地址 data = self.clearAddress(data) # print('=========================orderdetail 最终数据') # print(data) self.back2orderlist(pid, url, params) return data def back2order(self, id, url, params): # print('=========================后退到工单详情') params_new = params.copy() params_new['htmlbevt_ty'] = "htmlb:button:click:0" params_new['htmlbevt_oid'] = "C24_W111_V112_V113_thtmlb_button_1" params_new['thtmlbKeyboardFocusId'] = "C24_W111_V112_V113_thtmlb_button_1" params_new['htmlbevt_id'] = "done" params_new['htmlbevt_cnt'] = "0" params_new['sap-ajaxtarget'] = "C1_W1_V2_C1_W1_V2_V3_C24_W111_V112_C24_W111_V112_V113_PartnerEFHeader.do" params_new['sap-ajax_dh_mode'] = "AUTO" params_new['C13_W47_V48_SearchMenuAnchor1'] = "UP" params_new['C8_W34_V35_RecentObjects_isExpanded'] = "yes" self.session.post(url, data=params_new, headers=self.headers) def back2orderlist(self, id, url, params): # print('=========================返回工单列表') params_new = params params_new['htmlbevt_ty'] = "htmlb:link:click:null" params_new['htmlbevt_oid'] = "C1_W1_V2_V3_V55_back" params_new['thtmlbKeyboardFocusId'] = id params_new['htmlbevt_id'] = "back" params_new['htmlbevt_cnt'] = "1" params_new['htmlbevt_par1'] = "#" params_new['C23_W83_V84_V85_TextList_bindingString'] = "//Text/Table" params_new['C24_W88_V89_Table_selectedRows'] = "1" params_new['C24_W88_V89_Table_rowCount'] = "1" params_new['thtmlbOverviewControllerID'] = "C19_W69_V72" params_new['C28_W104_V105_Table_bindingString'] = "//DocList/Table" params_new['C28_W104_V105_Table_configHash'] = "2B1898492BCC377ECF844081E0C8B91EEB805379" params_new['C28_W104_V105_Table_multiParameter'] = "0////0////0////0" params_new['C19_W69_V72_0006_displaymode'] = "X" params_new['C27_W101_V102_ConfCellTable_multiParameter'] = "7D633AD0A8F7098E6A03D3F0BBA3020EB7F11686" params_new['C27_W101_V102_ConfCellTable_configHash'] = "0////0////0////0" params_new['C24_W88_V89_Table_allRowSelected'] = "FALSE" params_new['C25_W92_V93_V95_Table_bindingString'] = "//BTAdminI/Table" params_new['sap-ajaxtarget'] = "C1_W1_V2_C1_W1_V2_V3_C1_W1_V2_V3_V55_BreadCrumbView.do" self.session.post(url, data=params_new, headers=self.headers) if __name__ == '__main__': hdscrap = HDScrap('01007544', pwd='160324', adminid='24', bjdomain='http://gsn.bangjia.me') res = hdscrap.loginHd() # grap_res = hdscrap.transfer_order() # print(grap_res) grap_res = hdscrap.transfer_order(statuscode='M0010ZSIC0003') print(grap_res) # grap_res = hdscrap.transfer_order(statuscode='M0013ZSIC0004') # print(grap_res)
{"/SuningUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/huadi_zb.py": ["/Util.py"], "/TCSMCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/CDKCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/GreeUtil.py": ["/Util.py"], "/MideaUtil.py": ["/BaseUtil.py"], "/BaseUtil.py": ["/Util.py", "/cookie_test.py"], "/master.py": ["/searchutil.py"], "/login.py": ["/CDKUtil.py"], "/MideaCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/test/http2.py": ["/BaseUtil.py"], "/MIUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/JDUtil.py": ["/BaseUtil.py"], "/cookie_test.py": ["/aesgcm.py"]}
3,887
chengyan1984/cdk-gui
refs/heads/master
/searchutil.py
import json import requests base_url = "http://114.55.168.6/" search_api = base_url + "es-test/essearch.php" oper_api = base_url + "es-test/oper-search.php" # 操作类别:1:建单 2:派单 3:审核 4:结算 5:回访 def getAdminids(): params = dict() params['method'] = 'search' params['index'] = 'yxgoper' params['from'] = 0 params['size'] = 30 params['groupby'] = 'adminid' params['keyword'] = '' params['field_return'] = 'adminid' checkRes = requests.post(search_api, data=params) checkRes.encoding = 'utf-8' adminids = [] if checkRes and checkRes.status_code == 200: # print("获取所有网点id成功:") # print(checkRes.text) results = json.loads(checkRes.text) adminids.append('24') for element in results['element']: adminids.append(str(element['adminid'])) return adminids def getMasters(adminid): params = dict() params['method'] = 'search' params['index'] = 'yxgoper' params['from'] = 0 params['size'] = 100 params['groupby'] = 'username' params['keyword'] = '' params['field_return'] = ['username', 'userid'] params['adminid'] = adminid checkRes = requests.post(search_api, data=params) checkRes.encoding = 'utf-8' adminids = [] if checkRes and checkRes.status_code == 200: # print("获取所有网点id成功:") print(checkRes.text) results = json.loads(checkRes.text) adminids.append({'userid': '', 'username': '全部'}) for element in results['element']: adminids.append(element) return adminids # print(getMasters(24)) def getOperators(adminid, userid, start, end): params = dict() params['method'] = 'search' params['index'] = 'yxgoper' params['from'] = 0 params['size'] = 100 params['groupby'] = 'opertype' params['keyword'] = '' params['opertime'] = json.dumps([['egt', start], ['elt', end], 'and']) params['userids'] = json.dumps(userid) params['field_return'] = json.dumps(['username', 'opertype']) params['adminid'] = adminid checkRes = requests.post(oper_api, data=params) checkRes.encoding = 'utf-8' opers = [] if checkRes and checkRes.status_code == 200: # print("获取所有网点id成功:") print(checkRes.text) results = json.loads(checkRes.text) for element in results['element']: opers.append(element) return opers # print(getMasters('24')) # print(getOperators('24', ['250', '281', '23'], '2020-01-08 00:00:00', '2020-05-08 00:00:00'))
{"/SuningUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/huadi_zb.py": ["/Util.py"], "/TCSMCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/CDKCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/GreeUtil.py": ["/Util.py"], "/MideaUtil.py": ["/BaseUtil.py"], "/BaseUtil.py": ["/Util.py", "/cookie_test.py"], "/master.py": ["/searchutil.py"], "/login.py": ["/CDKUtil.py"], "/MideaCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/test/http2.py": ["/BaseUtil.py"], "/MIUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/JDUtil.py": ["/BaseUtil.py"], "/cookie_test.py": ["/aesgcm.py"]}
3,888
chengyan1984/cdk-gui
refs/heads/master
/TCSMCookieUtil.py
import io import json import re import sys import unicodedata from datetime import date, timedelta from urllib import parse import chardet import requests from idna import unicode from BaseUtil import BaseUtil from cookie_test import fetch_chrome_cookie class TCSMUtil(BaseUtil): def __init__(self, username, passwd, adminid='24', factoryid='6', baseurl='http://hk2.koyoo.cn/', bjdomain='http://yxgtest.bangjia.me'): super(TCSMUtil, self).__init__(username, passwd, adminid, factoryid, baseurl, bjdomain) self.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8' self.cookie = fetch_chrome_cookie([{"domain": ".koyoo.cn"}], isExact=False) self.cookies = BaseUtil.getCookies(self.cookie) self.headers['Cookie'] = self.cookie self.headers['Accept-Encoding'] = 'gzip, deflate' self.skills = [] def login(self, param=None): pass def islogin(self): self.headers['Accept'] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng," \ "*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" self.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8' self.headers['Referer'] = self.baseurl + 'index.php?m=index&f=index' url = self.baseurl + "index.php?m=workorder&f=handleIndex" response = self.session.get(url, headers=self.headers) bsObj = self.getsoup(response) skillselect = bsObj.find("select", {"id": "skill"}) if skillselect: skills = skillselect.find_all('option') self.skills = skills return skills is not None else: return False def loadOrders(self, param=None): if not self.islogin(): print("loadOrders is not login") return self.dataverify self.headers['Accept'] = "application/json, text/javascript, */*; q=0.01" self.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8' try: data = {"data": json.dumps(self.loadOrderbySkill())} requests.post(self.bjdomain + "/Api/Climborder/addorder", data=data) except Exception as e: print("loadOrders except:", e) return self.datafail return self.datasuccess def loadOrderbySkill(self): # print("loadOrderbySkill skills={}".format(self.skills)) results = [] for skill in self.skills: print("loadOrderbySkill skill={}".format(skill["value"])) # list(self.loadPageOrder(skill["value"])) results += list(self.loadPageOrder(skill["value"])) print("loadOrderbySkill results={}".format(results)) return results def loadPageOrder(self, skill=4209, page=1, totalcount=100, pageSize=100): dataurl = self.baseurl + "index.php?m=workorder&f=gridIndex" data = {"page": page, "rows": pageSize, "skillId": skill, "listType": "handle", "optid": "e7317288bb6d4849eec6dbe010d5d34e", "0[name]": "skill", "0[value]": skill, "1[name]": "Q|t2.dealstate|in", "1[value]": "OS_100,OS_400,OS_700,SS_W_REMIND", "27[name]": "isSearch", "27[value]": 1, "10[name]": "Q|t2.createtime|egt", "10[value]": BaseUtil.getDateBefore(3), "11[name]": "Q|t2.createtime|elt", "11[value]": BaseUtil.getDateBefore(0), } self.headers['Referer'] = dataurl # print("loadPageOrder data ={}".format(data)) response = self.session.post(dataurl, headers=self.headers, data=parse.urlencode(data)) response.encoding = 'gbk' resStr = response.text # sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='gb18030') print("loadOrders response={}".format(resStr)) resStr = re.sub(r'<label[^()]*?>', '', resStr) resStr = resStr.replace("<\\/label>", "") # resStr = resStr.encode("utf-8").decode("gbk") # resStr = resStr.encode("gbk", 'ignore').decode("utf-8", 'ignore') resStr = unicodedata.normalize('NFKD', resStr).encode('ascii', 'ignore').decode("utf-8", 'ignore') # resStr = resStr.encode("GBK", 'ignore').decode("unicode_escape") # print(chardet.detect(resStr)) # resStr = resStr.encode("utf-8").decode('unicode_escape') # """'gbk' codec can't encode character '\ufeff' in position 0: ???""" resStr = "{" + resStr print(resStr) if response.status_code == 200: result = json.loads(resStr) totalcount = result['total'] if page * pageSize >= totalcount: yield from self.parseOrders(result) else: yield from self.parseOrders(result) yield from self.loadPageOrder(page + 1, totalcount, pageSize) def parseOrders(self, data): for item in data['rows']: yield { 'factorynumber': self.parseHtml(item['worksn']), 'ordername': item['demandsmall'], 'username': item['customername'], 'mobile': item['customertel'], 'orderstatus': item['dealstate'], 'originname': item['srctype'], 'machinetype': item['probcate_id'], 'machinebrand': item['brand_id'], # 'sn': '', 'version': item['PRODUCT_MODEL'] if 'PRODUCT_MODEL' in item else '', 'repairtime': item['askdate'] + " " + (BaseUtil.getTimeStr(item['asktime'])), 'mastername': item['enginename'] if 'enginename' in item else '', # 'note': BeautifulSoup(item['processremark'], 'lxml').label.string, 'note': item['processremark'], 'companyid': self.factoryid, 'adminid': self.adminid, # 'address': BeautifulSoup(item['address'], 'lxml').label.string, 'address': item['address'], # 'province': item['provinceName'], 'city': item['cityName'], # 'county': item['regionName'], 'town': item['countyName'], 'ordertime': item['createtime'], # 'description': BeautifulSoup(item['clientrequirement'], 'lxml').label.string, 'description': item['clientrequirement'], } if __name__ == '__main__': # util = ConkaUtil('K608475', 'Kuser6646!', adminid='20699', factoryid='1') util = TCSMUtil('AW3306009461', 'Md123456789!', adminid='24', factoryid='4') # util = ConkaUtil('K608069', 'Crm@20200401', adminid='24', factoryid='1') print(util.loadOrders()) # print(util.loadPageOrder())
{"/SuningUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/huadi_zb.py": ["/Util.py"], "/TCSMCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/CDKCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/GreeUtil.py": ["/Util.py"], "/MideaUtil.py": ["/BaseUtil.py"], "/BaseUtil.py": ["/Util.py", "/cookie_test.py"], "/master.py": ["/searchutil.py"], "/login.py": ["/CDKUtil.py"], "/MideaCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/test/http2.py": ["/BaseUtil.py"], "/MIUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/JDUtil.py": ["/BaseUtil.py"], "/cookie_test.py": ["/aesgcm.py"]}
3,889
chengyan1984/cdk-gui
refs/heads/master
/CDKCookieUtil.py
import datetime import json import re import time from urllib import parse from urllib.parse import urlparse import requests from BaseUtil import BaseUtil from cookie_test import fetch_chrome_cookie class CDKCookieUtil(BaseUtil): def __init__(self, username='', passwd='', adminid='24', factoryid='18', baseurl='http://cdk.rrs.com', bjdomain='http://yxgtest.bangjia.me'): super(CDKCookieUtil, self).__init__(username, passwd, adminid, factoryid, baseurl, bjdomain) self.headers['Accept'] = "application/json, text/plain, */*" self.headers['Content-Type'] = 'application/json' self.cookie = fetch_chrome_cookie([{"domain": ".rrs.com"}], isExact=False) self.cookies = BaseUtil.getCookies(self.cookie) self.headers['Cookie'] = self.cookie self.azbaseurl = '' # cdk安装的baseurl,海尔安装单要用到:http://cdkaz.rrs.com self.azhost = '' # cdk安装的host:cdkaz.rrs.com def loadOrders(self, param=None): # # 开始加载工单 # self.headers['Accept'] = "*/*" # self.headers['Content-Type'] = 'application/json' # try: # data = {"data": json.dumps(list(self.loadPageOrder()))} # requests.post(self.bjdomain + "/Api/Climborder/addorder", data=data) # except: # return self.dataverify # return self.datasuccess # print(self.cookies) if not self.islogin(): return self.dataverify isSuccess = True haierRes = self.loadHaierOrder() # 抓取海尔工单 # print("loadHaierOrder result=", haierRes) isSuccess = isSuccess and haierRes['code'] == 1 netorder = self.loadWangdan() # 1: 表示维修 2 表示安装 3 表示鸿合维修单 4 表示清洁保养""" if not netorder: return self.dataverify netRes = self.loadNetworkOrder(netorder, 5) # 抓取网单 - 所有 isSuccess = isSuccess and netRes['code'] == 1 # netRes = self.loadNetworkOrder(netorder, 2) # 抓取网单 - 安装 # isSuccess = isSuccess and netRes['code'] == 1 # netRes = self.loadNetworkOrder(netorder, 1) # 抓取网单 - 维修 # isSuccess = isSuccess and netRes['code'] == 1 # netRes = self.loadNetworkOrder(netorder, 3) # 抓取网单 - 鸿合维修单 # isSuccess = isSuccess and netRes['code'] == 1 # netRes = self.loadNetworkOrder(netorder, 4) # 抓取网单 - 清洁保养 # isSuccess = isSuccess and netRes['code'] == 1 return self.datasuccess if isSuccess else self.datafail def islogin(self): url = self.baseurl + "/manager-web/index.do" if 'userCookie' in self.cookies: url += "?token=" + self.cookies['userCookie'] header = self.headers.copy() header[ 'Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' # header['Referer'] = self.baseurl response = self.session.get(url, headers=header) soup = self.getsoup(response) # print(soup) haierSpan = soup.find('span', text=re.compile('海尔安装')) # print("+++++++++++++++++++++++++++++++getHaierUrl") # print(haierSpan) if not haierSpan: return False parsed_url = urlparse(haierSpan['href']) self.azhost = parsed_url.netloc self.azbaseurl = parsed_url.scheme + "://" + parsed_url.netloc params = dict(parse.parse_qsl(parsed_url.query)) if 'token' not in params: return False token = params['token'] self.cookies['token'] = token # 进入海尔工单的验证流程 param = json.dumps({"token": params['token'], "moduleCode": "04", "userId": ""}) header = self.headers.copy() header['Host'] = self.azhost header['Origin'] = self.azbaseurl header['Referer'] = self.azbaseurl + "/pages/indexcdk?moduleCode=04&newTopWindow=true&token=" + token r0 = self.session.post(self.azbaseurl + "/api/system/authMenu/auth", data=param, headers=header) r = self.session.post(self.azbaseurl + "/api/system/authMenu/authMenuChanges", data=param, headers=header) # r2 = self.session.post(self.baseurl + "/manager-web/getCdkscIndexData.do", headers=header) return self.isSuccess(r0) and self.isSuccess(r) # and self.isSuccess(r2) def isSuccess(self, r): authresult = self.getjson(r) if not authresult or 'success' not in authresult or not authresult['success']: return False # if 'serviceCode' in authresult and authresult['serviceCode']: # self.serviceCode = authresult['serviceCode'] return True def loadWangdan(self): """加载网单页面""" url = self.baseurl + "/cdkwd/index2?moduleCode=02&token=" + self.cookies['token'] header = self.headers del header['Content-Type'] header[ 'Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' header['Referer'] = self.baseurl + "/manager-web/index.do?token=" + self.cookies['token'] header['Upgrade-Insecure-Requests'] = "1" response = self.session.get(url, headers=header) soup = self.getsoup(response) # print(soup) haierSpan = soup.find('div', text=re.compile('网单全流程')) print("+++++++++++++++++++++++++++++++loadWangdan") print(haierSpan) if not haierSpan: return False netorder = {'0': url, # '1': self.baseurl + soup.find('div', text=re.compile('维修单'))['href'], # '2': self.baseurl + soup.find('div', text=re.compile('安装单'))['href'], # '3': self.baseurl + soup.find('div', text=re.compile('鸿合维修单'))['href'], # '4': self.baseurl + soup.find('div', text=re.compile('清洁保养'))['href'] '5': self.baseurl + soup.find('div', text=re.compile('网单全流程'))['href'] } # 1: 表示维修 2 表示安装 3 表示鸿合维修单 4 表示清洁保养""" 5 表示全流程 return netorder def loadNetworkOrder(self, netorder, ordertype=2): """:ordertype = 5:所有网单 1: 表示维修 2 表示安装 3 表示鸿合维修单 4 表示清洁保养""" api_path = netorder[str(ordertype)] # print("***********************************loadNetworkOrder,url={}".format(apiPath)) header = self.headers header['Referer'] = netorder['0'] self.session.get(api_path, headers=header) header['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8' header[ 'Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' header['X-Requested-With'] = "XMLHttpRequest" header['Accept-Encoding'] = "gzip, deflate" header['Referer'] = api_path header['Upgrade-Insecure-Requests'] = '1' header['Cache-Control'] = 'max-age=0' apiPath = '/cdkwd/azdOrder/azdOrderList' if ordertype == 1: apiPath = '/cdkwd/repairOrder/repairOrderList' elif ordertype == 3: apiPath = '/cdkwd/wxRepairOrder/repairOrderList' elif ordertype == 4: apiPath = '/cdkwd/byOrder/byOrderList' elif ordertype == 5: apiPath = '/cdkwd/deliveryOrder/deliveryOrderList' today = datetime.date.today() # 获得今天的日期 pageUrl = self.baseurl + apiPath pageUrl = pageUrl + "?orderDateBegin=" + (today - datetime.timedelta(days=26)).strftime( '%Y-%m-%d') + "&orderDateEnd=" + datetime.date.today().strftime('%Y-%m-%d') pageUrl += "&orderCode=&orderId=&consignee=&length=150&consigneeMobile=&deliveryDateBegin=&deliveryDateEnd=&branchCodeYw=&orderStatus=&carDriver=&carPhone=&province=&city=&regionCode=&consigneeAddr=&carNo=&oldOrder=&isYy=&serviceArea=&serviceCodeYw=" # params = dict(parse.parse_qsl(parsed_url.query)) # print("pageUrl={}".format(pageUrl)) params = {} params['draw'] = "2" if ordertype == 2 else "1" # 1为维修 2为安装 params['order[0][column]'] = "2" params['order[0][dir]'] = "desc" params['start'] = 0 params['length'] = 150 orderRes = self.session.get(pageUrl, headers=header) orderRes.encoding = 'utf-8' # print("params=",params) # print("headers=",header) # print("loadNetworkOrder order result={}".format(orderRes.text)) if orderRes.status_code != 200 or not orderRes.text or len(orderRes.text.strip()) <= 0: return self.datafail orderResult = self.getjson(orderRes) if 'recordsTotal' in orderResult and orderResult['recordsTotal'] > 0: try: order_list = list(self.load_wd_orders(orderResult)) print(order_list) except Exception as e: error = self.datafail.copy() error['msg'] = str(e) return error checkRes = requests.post(self.bjdomain + "/Api/Climborder/addorder", data={"data": json.dumps(order_list)}) checkRes.encoding = 'utf-8' if checkRes and checkRes.status_code == 200: print("网单同步成功") return self.datasuccess return self.datasuccess def load_wd_orders(self, orderResult): # 加载网单列表 for r in orderResult['data']: description = "原单号:{},工单方式:{},司机:{}|{},联系人:{}|{}".format(r['sourceSn'], r['installWayName'] or '', r['carDriver'] or '', r['carPhone'] or '', r['fhContact'] or '', r['fhMobile'] or '') curtime = int(time.time()) r_time = r['reserveTime'] if r['reserveTime'] else r['deliveryDate'] or str(curtime) ordername = r['typeCodeName'] if "typeCodeName" in r and r['typeCodeName'] else "" order_info = {'factorynumber': r['orderId'], 'ordername': ordername, 'username': r['consignee'], 'mobile': r['consigneeMobile'], 'orderstatus': r['orderStatusName'], 'machinetype': r['add8'], 'province': r['province'], 'city': r['city'], 'county': r['region'], 'address': r['consigneeAddr'], 'description': r['add12'], 'ordertime': str(datetime.datetime.fromtimestamp(int(r['createdDate']) / 1000)), 'repairtime': str(datetime.datetime.fromtimestamp(int(r_time) / 1000)), 'buydate': str(datetime.datetime.fromtimestamp(int(r['accountDate']) / 1000)), 'machinebrand': '海尔', 'version': r['add5'], 'note': description, 'companyid': self.factoryid, 'adminid': self.adminid, 'originname': r['sourceCodeName'], 'branchCodeYw': r['branchCodeYw'], 'serviceCodeYw': r['serviceCodeYw'] } order_info = self.clearAddress(order_info) if not self.isNew(order_info, self.bjdomain, self.adminid): continue yield from self.load_wd_info(order_info) def load_wd_info(self, info): # 加载网单详情 info_url = self.baseurl + "/cdkwd/deliveryOrder/orderInfo?orderId={}&branchCode={}&serviceCode={}".format( info['factorynumber'], info['branchCodeYw'], info['serviceCodeYw']) res = self.session.get(info_url, headers=self.headers) soup = self.getsoup(res) # print("load_wd_info result=", soup) m = info['mobile'] c = m.count('*') # print("mobile=", m, "* count=", c) mobiles = re.findall(re.compile(r'[>]({})[<]'.format(m.replace("*" * c, "[0-9]{" + str(c) + "}"))), res.text) if mobiles and len(mobiles) > 0: mobile = mobiles[0] info['mobile'] = mobile.split('-')[0] info['description'] = "收货人手机:" + mobile machines = soup.find("tbody").find('tr').find_all('td') if machines and len(machines) > 5: info['machinebrand'] = machines[0].text.strip() info['machinetype'] = machines[1].text.strip() info['version'] = machines[5].text.strip().replace(info['machinebrand'], '').replace(info['machinetype'], "") info['sn'] = machines[4].text.strip() yield info def loadHaierOrder(self): pageUrl = self.azbaseurl + '/api/businessData/serviceList/selectServiceDealList' # print("***********************************loadHaierOrder,pageUrl=" + pageUrl) params = {} today = datetime.date.today() # 获得今天的日期 params['jobStatus'] = '1#3' # 只需要一种未派人状态 空则为全部, 1#3#4#5 params['regTimeStart'] = (today - datetime.timedelta(days=3)).strftime('%Y-%m-%d %H:%M:%S') params['regTimeEnd'] = (today + datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S') params['pageIndex'] = 1 params['rows'] = 50 params['token'] = self.cookies['token'] header = self.headers.copy() header['Referer'] = 'http://cdkaz.rrs.com/pages/cdkinstall/serveprocess' params = json.dumps(params) header['Content-Length'] = str(len(params)) header['Host'] = self.azhost header['Origin'] = self.azbaseurl # print("loadHaierOrder params:") # print("params=", params) # print("header=", header) # print("pageUrl=", pageUrl) orderRes = self.session.post(pageUrl, data=params, headers=header) # print(orderRes.text) orderResult = self.getjson(orderRes) if orderRes.status_code == 200 and 'success' in orderResult and orderResult['success'] and orderResult['data'] \ and 'records' in orderResult['data'] and orderResult['data']['records']: data = orderResult['data'] records = data['records'] pageCount = data['pageCount'] pageSize = data['pageSize'] rowCount = data['rowCount'] firstResult = data['firstResult'] # print(len(records)) print('pageCount=%s,pageSize=%s,rowCount=%s,firstResult=%s' % (pageCount, pageSize, rowCount, firstResult)) order_list = [] try: for record in records: ordername = record['orderFlagcode'] if record['orderFlagcode'] else "" order_info = {'factorynumber': record['woId'], 'ordername': ordername, 'username': record['customerName'], 'mobile': record['customerPhone'], 'orderstatus': '待派单', 'machinetype': record['productName'], 'address': record['address'], 'ordertime': record['assignDate'], 'repairtime': record['serviceDate'], 'description': record['reflectSituation'], 'version': record['modelName'], 'sn': record['model'], 'companyid': self.factoryid, 'machinebrand': '海尔', 'originname': 'CDK', 'adminid': self.adminid} order_list.append(order_info) except Exception as e: print(order_list) error = self.datafail.copy() error['msg'] = str(e) return error checkRes = requests.post(self.bjdomain + "/Api/Climborder/addorder", data={"data": json.dumps(order_list)}) checkRes.encoding = 'utf-8' if checkRes and checkRes.status_code == 200: print("海尔工单同步成功") return self.datasuccess return self.datasuccess if __name__ == '__main__': util = CDKCookieUtil('66004185', 'Dw147259', adminid='24', factoryid='18') print(util.loadOrders())
{"/SuningUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/huadi_zb.py": ["/Util.py"], "/TCSMCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/CDKCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/GreeUtil.py": ["/Util.py"], "/MideaUtil.py": ["/BaseUtil.py"], "/BaseUtil.py": ["/Util.py", "/cookie_test.py"], "/master.py": ["/searchutil.py"], "/login.py": ["/CDKUtil.py"], "/MideaCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/test/http2.py": ["/BaseUtil.py"], "/MIUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/JDUtil.py": ["/BaseUtil.py"], "/cookie_test.py": ["/aesgcm.py"]}
3,890
chengyan1984/cdk-gui
refs/heads/master
/GreeUtil.py
import json from datetime import date, timedelta from urllib.parse import urlparse, urlencode, unquote import requests from Util import Util class GreeUtil(Util): def __init__(self, username, passwd, adminid='15870', factoryid='1', baseurl='http://116.6.118.169:7909', bjdomain='http://fatest.bangjia.me'): parsed_uri = urlparse(baseurl) self.host = parsed_uri.netloc self.username = username self.passwd = passwd self.baseurl = baseurl self.adminid = adminid self.factoryid = factoryid self.bjdomain = bjdomain self.loginurl = self.baseurl + "/hjzx/loginAction_login" self.mainurl = self.loginurl self.searchurl = self.baseurl + '/hjzx/afterservice/afterservice!api.action' self.session = requests.Session() self.agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' \ 'Chrome/81.0.4044.113 Safari/537.36' self.datasuccess = {'code': 1, 'msg': '抓单成功', 'element': ''} self.datafail = {'code': 0, 'msg': '抓单失败,请确认账号密码是否正确'} self.headers = {'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': self.agent, 'Upgrade-Insecure-Requests': '1', 'Host': self.host, 'Referer': self.baseurl, 'Origin': parsed_uri.scheme + "://" + parsed_uri.netloc, 'Accept-Encoding': 'gzip, deflate', 'Connection': 'keep-alive', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,' '*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'} def isLogin(self): response = self.session.get(self.loginurl, headers=self.headers) response.encoding = 'utf-8' # print(response.status_code) # print("isLogin response={}".format(response.text)) return "新派工系统--&gt;主界面" in response.text def login(self): data = {"usid": self.username, "pswd": self.passwd, "loginflag": "loginflag"} response = self.session.post(self.loginurl, headers=self.headers, data=urlencode(data)) response.encoding = 'utf-8' # print("login result={}".format(response.text)) if response.status_code == 200: return "新派工系统--&gt;主界面" in response.text return False def loadMain(self): if not self.isLogin() and not self.login(): return self.datafail headers = self.headers.copy() headers['Referer'] = self.baseurl + '/hjzx/menu.jsp' # 加载安装工单查询 url = self.baseurl + "/hjzx/az/doListLcLsAz?otype=az&xsorsh=1&cd=pgcx" response = self.session.get(url, headers=headers) # response.encoding = 'utf-8' # print("loadMain response={}".format(response)) if response.status_code != 200: return self.datafail # return list(self.search(url)) try: data = {"data": json.dumps(list(self.search(url)))} # print("loadMain data = {}".format(data)) result = requests.post(self.bjdomain + "/Api/Climborder/addorder", data=data) # print(result.text) except Exception as e: print("addorder failed:", e) return self.datafail return self.datasuccess def search(self, url, page=1, totalcount=0, pagesize=50): headers = self.headers.copy() headers['Referer'] = url today = date.today() data = {"otype": "az", "xsorsh": "1", "cd": "pgcx", "s_azAssign.s_spid": "102", # 商用空调 "s_azAssign.s_cjdt_from": (today).strftime('%Y-%m-%d %H:%M:%S'), "s_azAssign.s_cjdt_to": (today + timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S'), "isFirstPage": "true" if page == 1 else "false", "paged": str(page) } response = self.session.post(self.baseurl + "/hjzx/az/doListLcLsAz", headers=headers, data=urlencode(data)) bsObj = self.getsoup(response) totalcount = int(bsObj.find("span", {"id": "totalRecord"}).text.strip()) print("search totalcount={}".format(totalcount)) # isall = (page + 1) * pagesize >= totalcount isall = True tbody = bsObj.find("table", {"id": "tbody"}).find("tbody") if isall: yield from self.parseOrders(tbody.find_all("tr")) else: yield from self.parseOrders(tbody.find_all("tr")) yield from self.search(url, page + 1, totalcount, pagesize) def parseOrders(self, trlist): for tr in trlist: tablecolumns = tr.find_all("td") if tr and len(tablecolumns) > 2: data = self.parseorder(tablecolumns) if data: detailUrl = self.baseurl + "/hjzx/az/" + tablecolumns[0].find("a")['href'] data = self.orderdetail(data, detailUrl) # print("parseorder data={}".format(data)) yield data def parseorder(self, tablecolumns): try: data = {} data['factorynumber'] = tablecolumns[2].text.strip() data['username'] = tablecolumns[4].text.strip() data['mobile'] = tablecolumns[5].text.strip() data['address'] = tablecolumns[6].text.strip() data['createname'] = tablecolumns[8].text.strip() data['ordertime'] = tablecolumns[9].text.strip() # 创建时间 data['companyid'] = self.factoryid data['machinebrand'] = "格力" data['machinetype'] = "商用空调" data['orgname'] = tablecolumns[10].text.strip() data['note'] = tablecolumns[12].text.strip() data['adminid'] = self.adminid data['description'] = "当前处理网点:{},处理结果跟踪:{},备注:{}".format( tablecolumns[10].text.strip(), tablecolumns[11].text.strip(), tablecolumns[12].text.strip()) # 具体描述 return data if self.isNew(data) else None except Exception as e: print("parseorder exception", e) return None def isNew(self, data): res = requests.post(self.bjdomain + "/Api/Climborder/checkexist", data={"orderno": data['factorynumber'], 'adminid': self.adminid}) return self.checkBjRes(res) def orderdetail(self, data, detailUrl): headers = self.headers.copy() headers['Referer'] = self.baseurl + "/hjzx/az/doListLcLsAz" # 加载安装工单查询 response = self.session.get(detailUrl, headers=headers) response.encoding = 'utf-8' # print(response.url) # print("orderdetail response={}".format(response.text)) if response.status_code != 200: return data bsObj = self.getsoup(response) # data['mastername'] = tablecolumns[10].text.strip() # 师傅姓名 无法获取 # data['mastermobile'] = tablecolumns[10].text.strip() # 师傅电话 无法获取 data['machineversion'] = str(bsObj.find("input", {"id": "jxid0"})["value"]) data['buydate'] = str(bsObj.find("input", {"id": "gmrq"})["value"]) data['repairtime'] = str(bsObj.find("input", {"id": "yyazsj"})["value"]) # 上门时间/预约安装时间 data['orderstatus'] = bsObj.find("span", {"id": "dqpgjd"}).text.strip() data['province'] = self.get_selected(bsObj.find("select", {"id": "sfen"})) data['city'] = self.get_selected(bsObj.find("select", {"id": "cshi"})) data['county'] = self.get_selected(bsObj.find("select", {"id": "xian"})) data['town'] = self.get_selected(bsObj.find("select", {"id": "jied"})) data['address'] = str(bsObj.find("input", {"id": "dizi"})["value"]) data['originname'] = self.get_selected(bsObj.find("select", {"id": "xslx"})) # 销售类型 作为工单来源 return data def logout(self): url = self.baseurl + "/hjzx/logout.jsp" self.headers['Referer'] = self.baseurl + '/hjzx/loginAction_login' self.session.get(url, headers=self.headers) if __name__ == '__main__': bjdomain = 'http://zjgl.bangjia.me' account = Util.getAccount(bjdomain) # print(account) # util = GreeUtil('S91898010070', 'S91898010070', adminid='24', factoryid='1') # print("loadMain result = {}".format(util.loadMain())) # util.logout() if account and 'loginname' in account and 'loginpwd' in account and 'adminid' in account and 'loginurl' in account: util = GreeUtil(account['loginname'], account['loginpwd'], adminid=account['adminid'], factoryid="10002", baseurl=unquote(account['loginurl']), bjdomain=bjdomain) print("gree loadMain result = {}".format(util.loadMain())) util.logout()
{"/SuningUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/huadi_zb.py": ["/Util.py"], "/TCSMCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/CDKCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/GreeUtil.py": ["/Util.py"], "/MideaUtil.py": ["/BaseUtil.py"], "/BaseUtil.py": ["/Util.py", "/cookie_test.py"], "/master.py": ["/searchutil.py"], "/login.py": ["/CDKUtil.py"], "/MideaCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/test/http2.py": ["/BaseUtil.py"], "/MIUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/JDUtil.py": ["/BaseUtil.py"], "/cookie_test.py": ["/aesgcm.py"]}
3,891
chengyan1984/cdk-gui
refs/heads/master
/aesgcm.py
import os import sys from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.ciphers import ( Cipher, algorithms, modes ) NONCE_BYTE_SIZE = 12 def encrypt(cipher, plaintext, nonce): cipher.mode = modes.GCM(nonce) encryptor = cipher.encryptor() ciphertext = encryptor.update(plaintext) return (cipher, ciphertext, nonce) def decrypt(cipher, ciphertext, nonce): cipher.mode = modes.GCM(nonce) decryptor = cipher.decryptor() return decryptor.update(ciphertext) def get_cipher(key): cipher = Cipher( algorithms.AES(key), None, backend=default_backend() ) return cipher
{"/SuningUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/huadi_zb.py": ["/Util.py"], "/TCSMCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/CDKCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/GreeUtil.py": ["/Util.py"], "/MideaUtil.py": ["/BaseUtil.py"], "/BaseUtil.py": ["/Util.py", "/cookie_test.py"], "/master.py": ["/searchutil.py"], "/login.py": ["/CDKUtil.py"], "/MideaCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/test/http2.py": ["/BaseUtil.py"], "/MIUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/JDUtil.py": ["/BaseUtil.py"], "/cookie_test.py": ["/aesgcm.py"]}
3,892
chengyan1984/cdk-gui
refs/heads/master
/CDKUtil.py
import datetime import json import os import re import random import sys from urllib import parse from urllib.parse import urlparse import requests from PIL import Image from io import BytesIO from bs4 import BeautifulSoup # from useragent import agents class CDKUtil: def __init__(self, username='', passwd='Dw147259', token=None): self.baseurl = "http://cdk.rrs.com" self.mainurl = 'http://cdk.rrs.com/manager-web/index.do' self.session = requests.Session() # self.agent = random.choice(agents) self.agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36' self.guidStr = CDKUtil.guid() self.token = token self.orderurl = '' self.username = username self.passwd = passwd @staticmethod def guid(): import uuid s_uuid = str(uuid.uuid4()) l_uuid = s_uuid.split('-') s_uuid = ''.join(l_uuid) s_uuid = s_uuid[:12] + "4" + s_uuid[13:] return s_uuid def generateCode(self): self.guidStr = CDKUtil.guid() # 动态加载验证码图片 captchaUrl = self.baseurl + "/login/generateCode?redisKey=" + self.guidStr print("generateCode guidStr=%s,captchaUrl=%s" % (self.guidStr, captchaUrl)) response = self.session.get(captchaUrl) return Image.open(BytesIO(response.content)) # _code = OCRUtil.getCode(img, config_cdk, tesseract_path) # print("generateCode captchaUrl: %s ,getCode :%s" % (captchaUrl, _code)) # 校验验证码 def checkCode(self, code, name, passwd): self.username = name self.passwd = passwd params = {"redisKey": self.guidStr, "checkCode": code} headers = {'content-type': 'application/json; charset=utf-8', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': self.agent, 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,pt;q=0.6', 'Connection': 'keep-alive', 'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8', 'Host': 'cdk.rrs.com'} checkRes = self.session.post(self.baseurl + "/login/checkCode", data=json.dumps(params), headers=headers) print('=========================checkCode') checkResult = json.loads(checkRes.text) # print(checkResult) # 验证码正确 if checkResult and checkResult['result'] == '1': print("=========================验证成功") codeFaultTimes = 0 return self.login(code, name, passwd) else: # 重新加载图片验证 验证码 return False def login(self, code, username, passwd): # 校验通过,模拟登陆 params = {"loginname": username, "loginpwd": passwd, "returnUrl": "http://cdk.rrs.com/manager-web/index.do", "checkCode": code} r = self.session.post(self.baseurl + "/login", data=params) r.encoding = 'utf-8' # 登录成功进入主界面 if r.status_code == 200: mainhtml = BeautifulSoup(r.text, features="lxml") # print(mainhtml) # print("=========================") # print(r.headers) return self.getHaierUrl(mainhtml) # 重定向到location elif r.status_code == 302: # location = r.headers.getheader('Location') location = r.headers['Location'] if location: # testcdk(name=name, passwd=passwd, url=location) return False # testcdk(name=name, passwd=passwd, url=baseurl + "/login.html?ReturnUrl=" + mainurl) return False def getHaierUrl(self, soap): # haierSpan = mainhtml.find("div", {"id": "serviceDiv"}).span haierSpan = soap.find('span', text=re.compile('海尔安装')) print("+++++++++++++++++++++++++++++++getHaierUrl") print(haierSpan) if not haierSpan: # testcdk(name=name, passwd=passwd, url=mainurl + "?token=" + self.token) return False haierUrl = haierSpan['href'] return self.loadHaier(haierUrl) # 加载海尔安装模块 def loadHaier(self, url): session = requests.Session() print("loadHaier url=" + url) haierMain = session.get(url) if haierMain.status_code == 200: soap = BeautifulSoup(haierMain.text, features="lxml") soap.encoding = 'utf-8' # print(soap) # 返回3个js polyfills.c38c86ad444630494a92.bundle.js main.4b3d8dea306811e889d6.bundle.js # http://cdkaz.rrs.com/inline.1557c7584b9dbbbbbcec.bundle.js return self.authAndgetMenu(url) # haierUrl = soap.find('a', text=re.compile('服务处理'))['href'] # orderMain = loadHaier(session, baseurl + haierUrl) # print(orderMain) else: return False # url = http://cdkaz.rrs.com/pages/cdkinstall/serveprocess?moduleCode=04&newTopWindow=true&token=168E4C1CDFF64967C3336A8ADF0CDB1B def authAndgetMenu(self, url): # 请求验证 auth = 'http://cdkaz.rrs.com//api/system/authMenu/auth' parsed_url = urlparse(url) print("========----------=============") print(parsed_url) haierBaseUrl = parsed_url.scheme + "://" + parsed_url.netloc pageUrl = haierBaseUrl + parsed_url.path params = dict(parse.parse_qsl(parsed_url.query)) self.token = params['token'] # 给全局变量赋值 token headers = {'content-type': 'application/json; charset=utf-8', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': self.agent, 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,pt;q=0.6', 'Connection': 'keep-alive', 'Accept': 'application/json, text/plain, */*', 'Host': parsed_url.netloc, 'Origin': haierBaseUrl} checkRes = self.session.post(auth, data=json.dumps(params), headers=headers) checkRes.encoding = 'utf-8' # print(checkRes.text) authResult = json.loads(checkRes.text) # {token=168E4C1CDFF64967C3336A8ADF0CDB1B moduleCode=04 userId=''} if checkRes.status_code == 200 and authResult['success']: menuUrl = 'http://cdkaz.rrs.com//api/system/authMenu/authMenuChanges' menuRes = self.session.post(menuUrl, data=json.dumps(params), headers=headers) menuRes.encoding = 'utf-8' menuResult = json.loads(menuRes.text) # print("========----------=============") # print(menuRes.text) if menuRes.status_code == 200 and menuResult['success']: for data in menuResult['data']: # print(data) # print("========") for children in data['children']: for childitem in children['children']: # print(childitem) # print("-------") if childitem['text'] == '服务处理': self.orderurl = haierBaseUrl + childitem['link'] + "?" + str(parse.urlencode(params)) self.updateUser(self.username, self.passwd, self.orderurl) return self.loadHaierOrder() return False # 重新登录 def loadHaierOrder(self): print("loadHaierOrder url=" + self.orderurl) parsed_url = urlparse(self.orderurl) apipath = '/api/businessData/serviceList/selectServiceDealList' print("***********************************") haierBaseUrl = parsed_url.scheme + "://" + parsed_url.netloc pageUrl = haierBaseUrl + apipath params = dict(parse.parse_qsl(parsed_url.query)) today = datetime.date.today() # 获得今天的日期 params['jobStatus'] = '1#3' # 只需要一种未派人状态 空则为全部, 1#3#4#5 params['regTimeStart'] = (today - datetime.timedelta(days=6)).strftime('%Y-%m-%d %H:%M:%S') params['regTimeEnd'] = (today + datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S') params['pageIndex'] = 1 params['rows'] = 50 headers = {'content-type': 'application/json', 'User-Agent': self.agent, 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,pt;q=0.6', 'Connection': 'keep-alive', 'Accept': 'application/json, text/plain, */*', 'Host': parsed_url.netloc, 'Origin': haierBaseUrl, 'Referer': self.orderurl} params = json.dumps(params) headers['Content-Length'] = str(len(params)) print("loadHaierOrder params:") # print(params) # print(headers) orderRes = self.session.post(pageUrl, data=params, headers=headers) orderRes.encoding = 'utf-8' # print(orderRes.text) orderResult = json.loads(orderRes.text) if orderRes.status_code == 200 and orderResult['success'] and orderResult['data']: data = orderResult['data'] records = data['records'] pageCount = data['pageCount'] pageSize = data['pageSize'] rowCount = data['rowCount'] firstResult = data['firstResult'] print(len(records)) print('pageCount=%s,pageSize=%s,rowCount=%s,firstResult=%s' % (pageCount, pageSize, rowCount, firstResult)) new_datas = {} order_list = [] for record in records: ordername = "安装" if "安装" in record['orderFlagcode'] else "维修" order_info = {'factorynumber': record['woId'], 'ordername': ordername, 'username': record['customerName'], 'mobile': record['customerPhone'], 'orderstatus': '待派单', 'machinetype': record['productName'], 'address': record['address'], 'ordertime': record['assignDate'], 'repairtime': record['serviceDate'], 'description': record['reflectSituation'], 'version': record['modelName'], 'sn': record['model'], 'companyid': 18, 'machinebrand': '海尔', 'originname': 'CDK', 'adminid': '26073'} order_list.append(order_info) checkRes = requests.post("http://north.bangjia.me/Api/Climborder/addorder", data={"data": json.dumps(order_list)}) checkRes.encoding = 'utf-8' if checkRes and checkRes.status_code == 200: print("同步成功") return True # for record in records: # new_datas[record['woId']] = Order(username=record['customerName'], orderno=record['woId'], # originno=record['sourceCode'], # mobile=record['customerPhone'], address=record['address'], # machineversion=record['modelName'], # data=json.dumps(record), token=token, uname=name) # for each in Order.query.filter(Order.orderno.in_(new_datas.keys())).all(): # # Only merge those posts which already exist in the database # # data = new_datas.pop(list(new_datas.keys()).index(each.orderno)) # data = new_datas.pop(each.orderno, None) # each.uname = name # # print("data=" + str(data)) # # if data: # # print("data orderno=" + data.orderno) # # db.session.merge(data) # # # Only add those posts which did not exist in the database # db.session.add_all(new_datas.values()) # # # Now we commit our modifications (merges) and inserts (adds) to the database! # db.session.commit() return False def updateUser(self, name, passwd, orderurl): userinfo = {"username": name, "passwd": passwd, "token": self.token, 'islogin': True, 'orderurl': orderurl} userfile = os.path.join(os.path.split(os.path.abspath(sys.argv[0]))[0], "file", "user.txt") with open(userfile, 'w') as f: jsObj = json.dumps(userinfo) f.write(jsObj) if __name__ == '__main__': # util = JDUtil('24', factoryid='19') util = CDKUtil()
{"/SuningUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/huadi_zb.py": ["/Util.py"], "/TCSMCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/CDKCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/GreeUtil.py": ["/Util.py"], "/MideaUtil.py": ["/BaseUtil.py"], "/BaseUtil.py": ["/Util.py", "/cookie_test.py"], "/master.py": ["/searchutil.py"], "/login.py": ["/CDKUtil.py"], "/MideaCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/test/http2.py": ["/BaseUtil.py"], "/MIUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/JDUtil.py": ["/BaseUtil.py"], "/cookie_test.py": ["/aesgcm.py"]}
3,893
chengyan1984/cdk-gui
refs/heads/master
/MideaUtil.py
import json import time from datetime import date, timedelta import requests from BaseUtil import BaseUtil class MideaUtil(BaseUtil): def __init__(self, username, passwd, adminid='24', factoryid='4', baseurl='https://cs.midea.com/c-css/', bjdomain='http://yxgtest.bangjia.me'): super(MideaUtil, self).__init__(username, passwd, adminid, factoryid, baseurl, bjdomain) self.headers['Accept'] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng," \ "*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" self.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8' self.dataverify = {'code': 2, 'msg': '输入验证码', 'element': ''} def login(self, param=None): self.headers['Accept'] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng," \ "*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" self.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8' if not param: loginurl = self.baseurl + "login" self.headers['Referer'] = loginurl response = self.session.get(loginurl, headers=self.headers) response.encoding = 'utf-8' print("login statuscode={}".format(response.status_code == 200)) print("login response={}".format(response.text)) if response.status_code == 200: result = self.loginauth() else: return self.getCaptcha() else: result = self.loginauth(param) print("login result={}".format(result)) print("param={}".format(param)) return param def getCaptcha(self): self.dataverify['url'] = self.baseurl + "captcha?r={}".format(round(time.time()*1000)) return self.dataverify def loginauth(self, param=None): code = param['code'] if param and 'code' in param else param if not code: if not self.checkState(): return self.getCaptcha() else: code = '' authurl = self.baseurl + "signin" data = {"userAccount": self.username, "userPassword": "6d904a32d4dbf2db15336eadca0d4802edfe2f85c0da02a32bff93b70c8d0b2c7181fd58c434c7838dd2b234feda762fbca546967a5ea7568958f55bc7966dd1", "captcha": code, "domainType": "CS"} print("loginauth data={}".format(data)) response = self.session.post(authurl, headers=self.headers, data=data) self.headers['Referer'] = authurl response.encoding = 'utf-8' print("loginauth result={}".format(response.text)) if response.status_code == 200: result = json.loads(response.text) if result and 'status' in result and result['status']: return self.loadOrders(True) return self.datafail def checkState(self): checkurl = self.baseurl + "captchaState" data = {"userAccount": self.username} response = self.session.post(checkurl, headers=self.headers, data=data) response.encoding = 'utf-8' result = False print("checkstate response={}".format(response.text)) if response.status_code == 200: state = json.loads(response.text) if state and 'content' in state and not state['content']: result = True else: result = False print("checkstate result={}".format(result)) return result def isLogin(self): self.headers['Accept'] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng," \ "*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" self.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8' mainurl = self.baseurl + "views/css/desktop/index.jsp" print(mainurl) response = self.session.get(mainurl, headers=self.headers) response.encoding = 'utf-8' print("loadOrders response={}".format(response.text)) if response.status_code == 200 and not response.text.startswith("<script>"): return True return False def loadOrders(self, param=None): if not param and not self.isLogin(): return self.login() try: data = {"data": json.dumps(list(self.loadPageOrder()))} requests.post(self.bjdomain + "/Api/Climborder/addorder", data=data) except: return self.datafail return self.datasuccess def loadPageOrder(self, page=1, totalcount=100, pageSize=100): # 开始加载工单 self.headers['Accept'] = "*/*" self.headers['Content-Type'] = 'application/json' dataurl = self.baseurl + "womflow/serviceorderunit/listdata" data = {"page": page, "rows": pageSize, "pageIndex": page - 1, "pageSize": pageSize, "formConditions": {"SERVICE_ORDER_STATUS": "", "CONTACT_TIME": (date.today() - timedelta(days=7)).strftime("%Y-%m-%d"), "CONTACT_TIME_end": (date.today()).strftime("%Y-%m-%d")}} response = self.session.post(dataurl, headers=self.headers, data=json.dumps(data)) self.headers['Referer'] = self.baseurl + "womflow/serviceorderunit/list?type=womServiceNotFinshCount" response.encoding = 'utf-8' print("loadOrders response={}".format(response.text)) result = json.loads(response.text) if result and 'status' in result and result['status']: data = result['content'] totalcount = data['total'] pagecount = data['pageCount'] pageSize = data['pageSize'] page = data['pageIndex'] print("totalcount={} pagecount={} pageSize={} page={}".format(totalcount, pagecount, pageSize, page)) if page >= pagecount: yield from self.parseOrders(data) else: yield from self.parseOrders(data) yield from self.loadPageOrder(page + 1, totalcount, pageSize) def parseOrders(self, data): for item in data['rows']: yield { 'factorynumber': item['SERVICE_ORDER_NO'], 'ordername': item['SERVICE_SUB_TYPE_NAME'], 'username': item['SERVICE_CUSTOMER_NAME'], 'mobile': item['SERVICE_CUSTOMER_TEL1'], 'orderstatus': item['SERVICE_ORDER_STATUS'], 'originname': item['ORDER_ORIGIN'], 'machinetype': item['PROD_NAME'], 'machinebrand': item['BRAND_NAME'], 'sn': '', 'version': item['PRODUCT_MODEL'] if 'PRODUCT_MODEL' in item else '', 'repairtime': item['FINAL_APPOINT_TIME'] if 'FINAL_APPOINT_TIME' in item else '', 'mastername': item['ENGINEER_NAME'] if 'ENGINEER_NAME' in item else '', 'note': item['PUB_REMARK'] if 'PUB_REMARK' in item else '', 'companyid': self.factoryid, 'adminid': self.adminid, 'address': str(item['SERVICE_CUSTOMER_ADDRESS']), # 'province': item['provinceName'], 'city': item['cityName'], # 'county': item['regionName'], 'town': item['countyName'], 'ordertime': item['CONTACT_TIME'], 'description': item['SERVICE_DESC'], } if __name__ == '__main__': # util = ConkaUtil('K608475', 'Kuser6646!', adminid='20699', factoryid='1') util = MideaUtil('AW3306009461', 'Md123456789!', adminid='24', factoryid='4') # util = MideaUtil('Aw3302060387', 'Jj62721262', adminid='24', factoryid='4') # util = ConkaUtil('K608069', 'Crm@20200401', adminid='24', factoryid='1') print(util.loadOrders())
{"/SuningUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/huadi_zb.py": ["/Util.py"], "/TCSMCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/CDKCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/GreeUtil.py": ["/Util.py"], "/MideaUtil.py": ["/BaseUtil.py"], "/BaseUtil.py": ["/Util.py", "/cookie_test.py"], "/master.py": ["/searchutil.py"], "/login.py": ["/CDKUtil.py"], "/MideaCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/test/http2.py": ["/BaseUtil.py"], "/MIUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/JDUtil.py": ["/BaseUtil.py"], "/cookie_test.py": ["/aesgcm.py"]}
3,894
chengyan1984/cdk-gui
refs/heads/master
/BaseUtil.py
import re from urllib.parse import urlparse import json import requests from bs4 import BeautifulSoup from datetime import date, timedelta, datetime from Util import Util from cookie_test import fetch_chrome_cookie class BaseUtil(Util): def __init__(self, username, passwd, adminid='15870', factoryid='1', baseurl='https://crm.konka.com', bjdomain='http://north.bangjia.me'): parsed_uri = urlparse(baseurl) self.host = parsed_uri.netloc self.username = username self.passwd = passwd self.baseurl = baseurl self.adminid = adminid self.factoryid = factoryid self.bjdomain = bjdomain self.mainurl = self.baseurl + '/admin/page!main.action' self.searchurl = self.baseurl + '/afterservice/afterservice!api.action' self.session = requests.Session() self.agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36' self.datasuccess = {'code': 1, 'msg': '抓单成功', 'element': ''} self.datafail = {'code': 0, 'msg': '抓单失败,请确认账号密码是否正确'} self.dataverify = {'code': 2, 'msg': '登录过期,请重新登录', 'element': ''} self.headers = {'Content-Type': 'application/json;charset=UTF-8', 'User-Agent': self.agent, 'Referer': self.baseurl, 'Upgrade-Insecure-Requests': '1', 'Host': self.host, 'Origin': self.baseurl, 'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive', 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2', 'Accept': 'application/json, text/plain, */*'} self.initCookie() def getsoup(self, response): response.encoding = 'utf-8' return BeautifulSoup(response.text, features="lxml") def parseHtml(self, htmlstr): bsObj = BeautifulSoup(htmlstr, features="lxml") if not bsObj: return "" return bsObj.text.strip() def getjson(self, response): response.encoding = 'utf-8' try: result = json.loads(response.text) except Exception as e: print("getjson failed:{}".format(str(e))) result = None return result @staticmethod def merge(lst1, lst2, keys, isCover=False): def generate_key(item): if type(keys) == list: return "_".join(str(v) for k, v in item.items() if k in keys) else: return "_".join(str(v) for k, v in item.items() if k == keys) hash_map = {} for item in lst1 + lst2: if isCover: hash_map[generate_key(item)] = item else: hash_map.setdefault(generate_key(item), item) result = list(hash_map.values()) return result if result else [] def initCookie(self, cookies=None): pass def login(self, param=None): pass def loadOrders(self, param=None): pass @staticmethod def getCookie(domains=[], isExact=False): return fetch_chrome_cookie(domains, isExact=isExact) @staticmethod def getCookies(cookie): cookies = dict([l.split("=", 1) for l in cookie.split("; ")]) return cookies @staticmethod def getDateBefore(day): return (date.today() - timedelta(days=day)).strftime("%Y-%m-%d") @staticmethod def clearKey(data, datakey, destkey='address'): if datakey in data and data[destkey] and data[destkey].strip().startswith(data[datakey].strip()): data[destkey] = data[destkey].replace(data[datakey], '', 1).strip() return data @staticmethod def clearAddress(orderinfo, destkey='address'): if destkey not in orderinfo: return orderinfo orderinfo = BaseUtil.clearKey(orderinfo, "province", destkey) orderinfo = BaseUtil.clearKey(orderinfo, "city", destkey) orderinfo = BaseUtil.clearKey(orderinfo, "county", destkey) orderinfo = BaseUtil.clearKey(orderinfo, "town", destkey) return orderinfo @staticmethod def getTimeStr(string, isDefault=True): defaultValue = '00:00:00' if isDefault else '' try: time_str = re.compile(r"\d{2}:\d{1,2}").findall(string)[0] result = time_str if BaseUtil.isTime(time_str) else defaultValue return result except IndexError: return defaultValue @staticmethod def isTime(time_str): return BaseUtil.isTimesecondstr(time_str) or BaseUtil.isTimestr(time_str) @staticmethod def isTimesecondstr(time_str): try: datetime.strptime(time_str, '%H:%M:%S') return True except ValueError: return False @staticmethod def isTimestr(time_str): try: datetime.strptime(time_str, '%H:%M') return True except ValueError: return False @staticmethod def isDatetimestr(datetime_str): try: datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S') return True except ValueError: return False # print("getDateBefore(0)={}".format(BaseUtil.getDateBefore(0)))
{"/SuningUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/huadi_zb.py": ["/Util.py"], "/TCSMCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/CDKCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/GreeUtil.py": ["/Util.py"], "/MideaUtil.py": ["/BaseUtil.py"], "/BaseUtil.py": ["/Util.py", "/cookie_test.py"], "/master.py": ["/searchutil.py"], "/login.py": ["/CDKUtil.py"], "/MideaCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/test/http2.py": ["/BaseUtil.py"], "/MIUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/JDUtil.py": ["/BaseUtil.py"], "/cookie_test.py": ["/aesgcm.py"]}
3,895
chengyan1984/cdk-gui
refs/heads/master
/master.py
import os import sys import time from datetime import datetime from datetime import timedelta import wx import wx.adv import wx.lib.mixins.inspection import wx.lib.mixins.listctrl as listmix import searchutil AppTitle = "报表管理" VERSION = 0.1 class MyListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin): def __init__(self, parent, id, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0): super(MyListCtrl, self).__init__(parent, id, pos, size, style) # ------------ listmix.ListCtrlAutoWidthMixin.__init__(self) # ------------ # Simplified init method. self.CreateColumns() self.SetProperties() # --------------------------------------------------------------------------- def CreateColumns(self): """ Create columns for listCtrl. """ self.InsertColumn(col=0, heading="ID", format=wx.LIST_FORMAT_LEFT) self.InsertColumn(col=1, heading="操作人", format=wx.LIST_FORMAT_LEFT) self.InsertColumn(col=2, heading="建单量", format=wx.LIST_FORMAT_LEFT) self.InsertColumn(col=3, heading="派单量", format=wx.LIST_FORMAT_LEFT) self.InsertColumn(col=4, heading="完工审核量", format=wx.LIST_FORMAT_LEFT) self.InsertColumn(col=5, heading="工资结算量", format=wx.LIST_FORMAT_LEFT) self.InsertColumn(col=6, heading="回访量", format=wx.LIST_FORMAT_LEFT) # ------------ # ASTUCE (Tip) - ListCtrlAutoWidthMixin : # pour diminuer le scintillement des colonnes # lors du redimensionnement de la mainframe, # regler la derniere colonne sur une largeur elevee. # Vous devez toujours visualiser l'ascenseur horizontal. # Set the width of the columns (x4). # Integer, wx.LIST_AUTOSIZE or wx.LIST_AUTOSIZE_USEHEADER. self.SetColumnWidth(col=0, width=50) self.SetColumnWidth(col=1, width=100) self.SetColumnWidth(col=2, width=60) self.SetColumnWidth(col=3, width=60) self.SetColumnWidth(col=4, width=110) self.SetColumnWidth(col=5, width=110) self.SetColumnWidth(col=6, width=60) def SetProperties(self): """ Set the list control properties (icon, font, size...). """ # Font size and style for listCtrl. fontSize = self.GetFont().GetPointSize() # Text attributes for columns title. # wx.Font(pointSize, family, style, weight, underline, faceName) if wx.Platform in ["__WXMAC__", "__WXGTK__"]: boldFont = wx.Font(fontSize - 1, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, "") self.SetForegroundColour("black") self.SetBackgroundColour("#ece9d8") # ecf3fd else: boldFont = wx.Font(fontSize, wx.DEFAULT, wx.NORMAL, wx.BOLD, False, "") self.SetForegroundColour("#808080") self.SetBackgroundColour("#ece9d8") # ecf3fd self.SetFont(boldFont) class MyFrame(wx.Frame): def __init__(self, parent, id, title, style=wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE | wx.CLIP_CHILDREN): super(MyFrame, self).__init__(parent=None, id=-1, title=title, style=style) # Returns application name. self.app_name = wx.GetApp().GetAppName() # Returns bitmaps folder. self.bitmaps_dir = wx.GetApp().GetBitmapsDir() # Returns icons folder. self.icons_dir = wx.GetApp().GetIconsDir() # Simplified init method. self.getAdminids() # 获取所有的网点 self.getMasters(0) # 获取网点下的所有师傅 self.SetProperties() # 设置界面的属性 self.MakeMenuBar() self.MakeStatusBar() self.CreateCtrls() self.BindEvents() self.DoLayout() self.OnTimer(None) self.timer = wx.Timer(self) self.timer.Start(3000) self.Bind(wx.EVT_TIMER, self.OnTimer) def getAdminids(self): pass def getMasters(self, adminid): pass def SetProperties(self): """ Set the frame properties (title, icon, size...). """ # Setting some frame properties. frameIcon = wx.Icon(os.path.join(self.icons_dir, "icon_wxWidgets.ico"), type=wx.BITMAP_TYPE_ICO) self.SetIcon(frameIcon) # Frame cursor. cursorHand = wx.Cursor(os.path.join(self.icons_dir, "hand.cur"), type=wx.BITMAP_TYPE_CUR) self.SetCursor(cursorHand) self.SetTitle("%s V%.1f" % (self.app_name, VERSION)) def MakeMenuBar(self): # Set an icon to the exit/about menu item. emptyImg = wx.Bitmap(os.path.join(self.bitmaps_dir, "item_empty.png"), type=wx.BITMAP_TYPE_PNG) exitImg = wx.Bitmap(os.path.join(self.bitmaps_dir, "item_exit.png"), type=wx.BITMAP_TYPE_PNG) helpImg = wx.Bitmap(os.path.join(self.bitmaps_dir, "item_about.png"), type=wx.BITMAP_TYPE_PNG) # menu. mnuFile = wx.Menu() mnuInfo = wx.Menu() # mnuFile. # Show how to put an icon in the menu item. menuItem1 = wx.MenuItem(mnuFile, -1, "布局查看\tCtrl+Alt+I", "布局查看工具 !") menuItem1.SetBitmap(emptyImg) mnuFile.Append(menuItem1) self.Bind(wx.EVT_MENU, self.OnOpenWidgetInspector, menuItem1) # Show how to put an icon in the menu item. menuItem2 = wx.MenuItem(mnuFile, wx.ID_EXIT, "退出\tCtrl+Q", "关闭 !") menuItem2.SetBitmap(exitImg) mnuFile.Append(menuItem2) self.Bind(wx.EVT_MENU, self.OnExit, menuItem2) # mnuInfo. # Show how to put an icon in the menu item. menuItem2 = wx.MenuItem(mnuInfo, wx.ID_ABOUT, "关于\tCtrl+A", "关于软件 !") menuItem2.SetBitmap(helpImg) mnuInfo.Append(menuItem2) self.Bind(wx.EVT_MENU, self.OnAbout, menuItem2) # menuBar. menubar = wx.MenuBar() # Add menu voices. menubar.Append(mnuFile, "文件") menubar.Append(mnuInfo, "关于") self.SetMenuBar(menubar) def MakeStatusBar(self): """ Create the status bar for my frame. """ # Statusbar. self.myStatusBar = self.CreateStatusBar(1) self.myStatusBar.SetFieldsCount(2) self.myStatusBar.SetStatusWidths([-8, -4]) self.myStatusBar.SetStatusText("", 0) self.myStatusBar.SetStatusText("bangjia.me.", 1) def getTodayDate(self, _date, _type): now = _date print(type(now)) zero_date = now - timedelta(hours=now.hour, minutes=now.minute, seconds=now.second, microseconds=now.microsecond) if _type == 0: return zero_date else: return zero_date + timedelta(hours=23, minutes=59, seconds=59) def CreateCtrls(self): """ Create some controls for my frame. """ # Font style for wx.StaticText. font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) font.SetWeight(wx.BOLD) self.adminid = None self.masters = None self.userids = [] self.startdate = self.getTodayDate(datetime.now(), 0) self.enddate = self.getTodayDate(datetime.now(), 1) # Widgets. self.panel = wx.Panel(self) # self.stEmployees = wx.StaticText(self.panel, -1, "Employees list :") # self.stEmployees.SetForegroundColour("gray") # self.stEmployees.SetFont(font) # Image list. self.il = wx.ImageList(16, 16, True) # Set an icon for the first column. self.bmp = wx.Bitmap(os.path.join(self.bitmaps_dir, "employee.png"), type=wx.BITMAP_TYPE_PNG) # Add image to list. self.img_idx = self.il.Add(self.bmp) self.listCtrl = MyListCtrl(self.panel, -1, style=wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_VRULES | wx.BORDER_SUNKEN) # Assign the image list to it. self.listCtrl.SetImageList(self.il, wx.IMAGE_LIST_SMALL) # Retrieve data from the database. # self.employeeData = self.OnLoadData() # # # Populate the wx.ListCtrl. # for i in self.employeeData: # index = self.listCtrl.InsertItem(self.listCtrl.GetItemCount(), # ((str(i[0])))) # self.listCtrl.SetItem(index, 1, i[1]) # self.listCtrl.SetItem(index, 2, i[2]) # self.listCtrl.SetItem(index, 3, i[3]) # self.listCtrl.SetItem(index, 4, i[4]) # self.listCtrl.SetItemImage(self.listCtrl.GetItemCount() - 1, # self.img_idx) # # # Alternate the row colors of a ListCtrl. # # Mike Driscoll... thank you ! # if index % 2: # self.listCtrl.SetItemBackgroundColour(index, "#ffffff") # else: # self.listCtrl.SetItemBackgroundColour(index, "#ece9d8") # ecf3fd self.stSearch = wx.StaticText(self.panel, -1, 'Search "Surname" :') self.txSearch = wx.TextCtrl(self.panel, -1, "", size=(100, -1)) self.txSearch.SetToolTip("Search employee !") self.StaticSizer = wx.StaticBox(self.panel, -1, "Commands :") self.StaticSizer.SetForegroundColour("red") self.StaticSizer.SetFont(font) self.bntSearch = wx.Button(self.panel, -1, "搜索") self.bntSearch.SetToolTip("搜索角色的操作单量 !") self.bntClear = wx.Button(self.panel, -1, "&Clear") self.bntClear.SetToolTip("Clear the search text !") self.bntShowAll = wx.Button(self.panel, -1, "&All") self.bntShowAll.SetToolTip("Show all !") self.bntNew = wx.Button(self.panel, -1, "&Insert") self.bntNew.SetToolTip("Insert a new employee !") self.bntEdit = wx.Button(self.panel, -1, "&Update") self.bntEdit.SetToolTip("Update selected employee !") self.bntDelete = wx.Button(self.panel, -1, "&Delete") self.bntDelete.SetToolTip("Delete selected employee !") self.bntClose = wx.Button(self.panel, -1, "&Quit") self.bntClose.SetToolTip("Close !") # 创建操作区元素 self.wangdian_text = wx.StaticText(self.panel, -1, "选择网点:") self.master_text = wx.StaticText(self.panel, -1, "选择操作人:") self.time_text = wx.StaticText(self.panel, -1, "操作时间:") self.to_text = wx.StaticText(self.panel, -1, "到") # ch1 = wx.ComboBox(self.panel, -1, value='C', choices=searchutil.getAdminids(), style=wx.CB_SORT) self.ch_adminid = wx.Choice(self.panel, -1, choices=searchutil.getAdminids()) self.ch_master = wx.Choice(self.panel, -1, choices=['全部']) self.start = wx.adv.DatePickerCtrl(self.panel, -1, size=(120, 22), style=wx.adv.DP_DROPDOWN | wx.adv.DP_SHOWCENTURY) self.end = wx.adv.DatePickerCtrl(self.panel, -1, size=(120, 22), style=wx.adv.DP_DROPDOWN | wx.adv.DP_SHOWCENTURY) self.ch_adminid.SetSelection(0) self.adminid = 24 self.getAllMasters() def BindEvents(self): """ 添加事件处理 """ # self.txSearch.Bind(wx.EVT_TEXT, self.OnUpperCaseText) # # # Intercept the click on the wx.ListCtrl. # self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self.listCtrl) # self.Bind(wx.EVT_LIST_COL_BEGIN_DRAG, self.OnColBeginDrag, self.listCtrl) # self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated, self.listCtrl) # self.Bind(wx.EVT_BUTTON, self.OnSearch, self.bntSearch) # self.Bind(wx.EVT_BUTTON, self.OnClear, self.bntClear) # self.Bind(wx.EVT_BUTTON, self.OnShowAll, self.bntShowAll) # self.Bind(wx.EVT_BUTTON, self.OnNew, self.bntNew) # self.Bind(wx.EVT_BUTTON, self.OnEdit, self.bntEdit) # self.Bind(wx.EVT_BUTTON, self.OnDelete, self.bntDelete) self.Bind(wx.EVT_BUTTON, self.OnExit, self.bntClose) self.Bind(wx.EVT_CLOSE, self.OnExit) self.Bind(wx.EVT_CHOICE, self.on_choice_a, self.ch_adminid) self.Bind(wx.EVT_CHOICE, self.on_choice_m, self.ch_master) self.Bind(wx.adv.EVT_DATE_CHANGED, self.OnDateChanged, self.start) self.Bind(wx.adv.EVT_DATE_CHANGED, self.OnDateChanged2, self.end) def DoLayout(self): # Sizer. actionSizer = wx.BoxSizer(wx.HORIZONTAL) textSizer = wx.BoxSizer(wx.VERTICAL) mainSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer = wx.StaticBoxSizer(self.StaticSizer, wx.VERTICAL) # Assign widgets to sizers. # actionSizer # actionSizer.Add(self.stEmployees, 0, wx.BOTTOM, 5) actionSizer.Add(self.wangdian_text, 0, flag=wx.LEFT | wx.RIGHT | wx.FIXED_MINSIZE, border=5) actionSizer.Add(self.ch_adminid, 0, flag=wx.LEFT | wx.RIGHT | wx.FIXED_MINSIZE, border=5) actionSizer.Add(self.master_text, 0, flag=wx.LEFT | wx.RIGHT | wx.FIXED_MINSIZE, border=5) actionSizer.Add(self.ch_master, 0, flag=wx.LEFT | wx.RIGHT | wx.FIXED_MINSIZE, border=5) actionSizer.Add(self.time_text, 0, flag=wx.LEFT | wx.RIGHT | wx.FIXED_MINSIZE, border=5) actionSizer.Add(self.start, 0, flag=wx.LEFT | wx.RIGHT | wx.FIXED_MINSIZE) actionSizer.Add(self.to_text, 0, flag=wx.LEFT | wx.RIGHT | wx.FIXED_MINSIZE, border=5) actionSizer.Add(self.end, 0, flag=wx.LEFT | wx.RIGHT | wx.FIXED_MINSIZE) actionSizer.Add(self.bntSearch, 0, wx.ALL, border=5) # textSizer. textSizer.Add(actionSizer, 0, wx.BOTTOM, 10) textSizer.Add(self.listCtrl, 1, wx.EXPAND) # btnSizer. btnSizer.Add(self.stSearch) btnSizer.Add(self.txSearch) # btnSizer.Add((5, 5), -1) # btnSizer.Add(self.bntSearch, 0, wx.ALL, 5) btnSizer.Add((5, 5), -1) btnSizer.Add(self.bntClear, 0, wx.ALL, 5) btnSizer.Add((5, 5), -1) btnSizer.Add(self.bntShowAll, 0, wx.ALL, 5) btnSizer.Add((5, 5), -1) btnSizer.Add(self.bntNew, 0, wx.ALL, 5) btnSizer.Add((5, 5), -1) btnSizer.Add(self.bntEdit, 0, wx.ALL, 5) btnSizer.Add((5, 5), -1) btnSizer.Add(self.bntDelete, 0, wx.ALL, 5) btnSizer.Add((5, 5), -1) btnSizer.Add(self.bntClose, 0, wx.ALL, 5) # Assign to mainSizer the other sizers. mainSizer.Add(textSizer, 1, wx.ALL | wx.EXPAND, 10) mainSizer.Add(btnSizer, 0, wx.ALL, 10) mainSizer.Hide(btnSizer) # Assign to panel the mainSizer. self.panel.SetSizer(mainSizer) mainSizer.Fit(self) # mainSizer.SetSizeHints(self) def OnOpenWidgetInspector(self, event): """ Activate the widget inspection tool, giving it a widget to preselect in the tree. Use either the one under the cursor, if any, or this frame. """ from wx.lib.inspection import InspectionTool wnd = wx.FindWindowAtPointer() if not wnd: wnd = self InspectionTool().Show(wnd, True) def on_combobox(self, event): print("选择{0}".format(event.GetString())) def on_choice_a(self, event): self.adminid = event.GetString() print("选择网点id:{}".format(self.adminid)) self.ch_master.Clear() self.getAllMasters() def getAllMasters(self): self.masters = searchutil.getMasters(self.adminid) # masterStr = [] # self.ch_master.Client(0, None) for index, master in enumerate(self.masters): if index != 0: self.userids.append(str(master['userid'])) # masterStr.append(str(master['username'])) self.ch_master.Append(master['username'], master) # self.ch_master.SetItems(masterStr) # 可行 self.ch_master.SetSelection(0) def on_choice_m(self, event): print("选择操作人:{}".format(event.GetString())) print("选择到操作人的其他参数:{}".format(event.GetClientData())) def OnDateChanged(self, evt): print("OnDateChanged: %s\n" % evt.GetDate()) # self.log.write("OnDateChanged: %s\n" % evt.GetDate()) self.startdate = self.getTodayDate(wx.wxdate2pydate(evt.GetDate()), 0) print("OnDateChanged2 startdate: %s\n" % self.startdate) pass def OnDateChanged2(self, evt): print("OnDateChanged2: %s\n" % evt.GetDate()) # self.log.write("OnDateChanged2: %s\n" % evt.GetDate()) self.enddate = self.getTodayDate(wx.wxdate2pydate(evt.GetDate()), 1) print("OnDateChanged2 enddate: %s\n" % self.enddate) pass def OnSearch(self, event): print("OnSearch") # print(self.ch_adminid.GetSelection()) # 选中的索引 # itemObject = self.ch_adminid.GetClientData(self.ch_adminid.GetSelection()) if self.ch_master.GetSelection() == 0: # userid = self.ch_master.GetItems() # 获取到了所有的展示名称列表 userid = self.userids else: userid = self.ch_master.GetClientData(self.ch_master.GetSelection()) print("adminid={}, userid={}".format(self.adminid, userid)) print("startdate={}, enddate={}".format(self.startdate, self.enddate)) self.updateList(searchutil.getOperators(self.adminid, userid, self.startdate.strftime('%Y-%m-%d %H:%M:%S'), self.enddate.strftime('%Y-%m-%d %H:%M:%S'))) pass def updateList(self, datas): self.listCtrl.SetFocus() self.listCtrl.DeleteAllItems() print(datas) # Populate the wx.ListCtrl. for _index, _data in enumerate(datas): index = self.listCtrl.InsertItem(self.listCtrl.GetItemCount(),str(_index + 1)) if not _data['datas']: print() for items in _data['datas']: print(items) data = {} username = '' # 操作类别:1:建单 2:派单 3:审核 4:结算 5:回访 for item in items: username = item['username'] data[str(item['opertype'])] = item['total_count'] self.listCtrl.SetItem(index, 1, username) self.listCtrl.SetItem(index, 2, 0 if '1' not in data else data['1']) self.listCtrl.SetItem(index, 3, 0 if '2' not in data else data['2']) self.listCtrl.SetItem(index, 4, 0 if '3' not in data else data['3']) self.listCtrl.SetItem(index, 5, 0 if '4' not in data else data['4']) self.listCtrl.SetItem(index, 6, 0 if '5' not in data else data['5']) self.listCtrl.SetItemImage(self.listCtrl.GetItemCount() - 1, self.img_idx) # Alternate the row colors of a ListCtrl. # Mike Driscoll... thank you ! if index % 2: self.listCtrl.SetItemBackgroundColour(index, "#ffffff") else: self.listCtrl.SetItemBackgroundColour(index, "#ece9d8") # ecf3fd @ staticmethod def OnAbout(event): message = """wangdian.bangjia.me\n 帮家报表管理系统 使用wxPython开发.\n 当前版本 : %.1f""" % VERSION wx.MessageBox(message, AppTitle, wx.OK) def OnClose(self): ret = wx.MessageBox("确定要退出吗 ?", AppTitle, wx.YES_NO | wx.ICON_QUESTION | wx.CENTRE | wx.NO_DEFAULT) return ret def OnExit(self, event): # Ask for exit. intChoice = self.OnClose() if intChoice == 2: # Disconnect from server. # self.con.OnCloseDb() self.Destroy() def OnTimer(self, event): t = time.localtime(time.time()) sbTime = time.strftime("当前时间 %d/%m/%Y are %H:%M:%S", t) self.myStatusBar.SetStatusText(sbTime, 0) class MyApp(wx.App, wx.lib.mixins.inspection.InspectionMixin): def OnInit(self, redirect=False, filename=None, useBestVisual=False, clearSigInt=True): self.SetAppName("帮家报表系统") self.InitInspection() self.installDir = os.path.split(os.path.abspath(sys.argv[0]))[0] self.locale = wx.Locale(wx.LANGUAGE_CHINESE_SIMPLIFIED) print("OnInit sys.argv[0]={}".format(sys.argv[0])) print("OnInit installDir={}".format(self.installDir)) frame = MyFrame(None, -1, title="") frame.SetSize(800, 527) self.SetTopWindow(frame) frame.Center() frame.Show(True) return True def GetInstallDir(self): """ Returns the installation directory for my application. """ return self.installDir def GetIconsDir(self): """ Returns the icons directory for my application. """ icons_dir = os.path.join(self.installDir, "icons") return icons_dir def GetBitmapsDir(self): """ Returns the bitmaps directory for my application. """ bitmaps_dir = os.path.join(self.installDir, "bitmaps") return bitmaps_dir def main(): app = MyApp(redirect=False) app.MainLoop() if __name__ == "__main__": main()
{"/SuningUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/huadi_zb.py": ["/Util.py"], "/TCSMCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/CDKCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/GreeUtil.py": ["/Util.py"], "/MideaUtil.py": ["/BaseUtil.py"], "/BaseUtil.py": ["/Util.py", "/cookie_test.py"], "/master.py": ["/searchutil.py"], "/login.py": ["/CDKUtil.py"], "/MideaCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/test/http2.py": ["/BaseUtil.py"], "/MIUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/JDUtil.py": ["/BaseUtil.py"], "/cookie_test.py": ["/aesgcm.py"]}
3,896
chengyan1984/cdk-gui
refs/heads/master
/test_text.py
#!/usr/bin/env python import time import wx import wx.adv #---------------------------------------------------------------------- class TestPanel(wx.Panel): def __init__(self, parent, log): self.log = log wx.Panel.__init__(self, parent, -1) textSizer = wx.BoxSizer(wx.VERTICAL) # self.stEmployees = wx.StaticText(self, -1, "你好,这个是测试文本", style=wx.ALIGN_CENTER) # self.stEmployees.SetForegroundColour("gray") # self.stEmployees.SetFont(font) # textSizer.Add(self.stEmployees, flag=wx.CENTER) title = wx.StaticText(self, -1, "This is an example of static text", style=wx.ALIGN_CENTER) center = wx.StaticText(self, -1, "align center", style=wx.ALIGN_CENTER) center.SetForegroundColour('white') center.SetBackgroundColour('black') textSizer.Add(title, 0, wx.EXPAND, 10) textSizer.Add(center, 0, wx.EXPAND, 10) self.SetSizer(textSizer) textSizer.Fit(self) import datetime def subtime(date1, date2): date1 = datetime.datetime.strptime(date1, "%Y-%m-%d %H:%M:%S") date2 = datetime.datetime.strptime(date2, "%Y-%m-%d %H:%M:%S") return date2 - date1 date1 = r'2015-06-19 02:38:01' date2 = r'2015-06-18 05:31:22' # print(time.gmtime()) print(subtime(date1, date2)) # date1 > date2 print(subtime(date2, date1)) # date1 < date2 nowdate = datetime.datetime.now() # 获取当前时间 nowdate = nowdate.strftime("%Y-%m-%d %H:%M:%S") # 当前时间转换为指定字符串格式 print(subtime(date2, nowdate)) # nowdate > date2 # In some cases the widget used above will be a native date # picker, so show the generic one too. # dpc = wx.adv.DatePickerCtrlGeneric(self, size=(120,-1), # style = wx.TAB_TRAVERSAL # | wx.adv.DP_DROPDOWN # | wx.adv.DP_SHOWCENTURY # | wx.adv.DP_ALLOWNONE ) # self.Bind(wx.adv.EVT_DATE_CHANGED, self.OnDateChanged, dpc) # sizer.Add(dpc, 0, wx.LEFT, 50) def OnDateChanged(self, evt): self.log.write("OnDateChanged: %s\n" % evt.GetDate()) #---------------------------------------------------------------------- def runTest(frame, nb, log): win = TestPanel(nb, log) return win #---------------------------------------------------------------------- overview = """<html><body> <h2><center>wx.DatePickerCtrl</center></h2> This control allows the user to select a date. Unlike wx.calendar.CalendarCtrl, which is a relatively big control, wx.DatePickerCtrl is implemented as a small window showing the currently selected date. The control can be edited using the keyboard, and can also display a popup window for more user-friendly date selection, depending on the styles used and the platform. </body></html> """ if __name__ == '__main__': import sys,os import run run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])
{"/SuningUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/huadi_zb.py": ["/Util.py"], "/TCSMCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/CDKCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/GreeUtil.py": ["/Util.py"], "/MideaUtil.py": ["/BaseUtil.py"], "/BaseUtil.py": ["/Util.py", "/cookie_test.py"], "/master.py": ["/searchutil.py"], "/login.py": ["/CDKUtil.py"], "/MideaCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/test/http2.py": ["/BaseUtil.py"], "/MIUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/JDUtil.py": ["/BaseUtil.py"], "/cookie_test.py": ["/aesgcm.py"]}
3,897
chengyan1984/cdk-gui
refs/heads/master
/test/test_re.py
import re string = "originOrgId: 'WDCN02431'," print(re.findall(re.compile(r"originOrgId: ['](.*?)[']", re.S), string)[0])
{"/SuningUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/huadi_zb.py": ["/Util.py"], "/TCSMCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/CDKCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/GreeUtil.py": ["/Util.py"], "/MideaUtil.py": ["/BaseUtil.py"], "/BaseUtil.py": ["/Util.py", "/cookie_test.py"], "/master.py": ["/searchutil.py"], "/login.py": ["/CDKUtil.py"], "/MideaCookieUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/test/http2.py": ["/BaseUtil.py"], "/MIUtil.py": ["/BaseUtil.py", "/cookie_test.py"], "/JDUtil.py": ["/BaseUtil.py"], "/cookie_test.py": ["/aesgcm.py"]}