index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
21,614
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/e334c53b9bba_add_columns_to_tracking_info.py
|
"""add_columns_to_tracking_info
Revision ID: e334c53b9bba
Revises: 901a4674cb12
Create Date: 2017-03-08 10:19:02.648204
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e334c53b9bba'
down_revision = '901a4674cb12'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('tracking_info', sa.Column('delivery_man_name', sa.String(length=200), nullable=True))
op.add_column('tracking_info', sa.Column('logistics_company', sa.String(length=200), nullable=True))
op.add_column('tracking_info', sa.Column('production_ends_at', sa.DateTime(), nullable=True))
op.add_column('tracking_info', sa.Column('production_manager', sa.String(length=200), nullable=True))
op.add_column('tracking_info', sa.Column('production_starts_at', sa.DateTime(), nullable=True))
op.add_column('tracking_info', sa.Column('qrcode_image', sa.String(length=200), nullable=True))
op.add_column('tracking_info', sa.Column('qrcode_token', sa.String(length=128), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('tracking_info', 'qrcode_token')
op.drop_column('tracking_info', 'qrcode_image')
op.drop_column('tracking_info', 'production_starts_at')
op.drop_column('tracking_info', 'production_manager')
op.drop_column('tracking_info', 'production_ends_at')
op.drop_column('tracking_info', 'logistics_company')
op.drop_column('tracking_info', 'delivery_man_name')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,615
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/tests/test.py
|
# -*- coding: utf-8 -*-
import unittest
from flask import request
from application import app
import json
class HttpTest(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
def test_get_root_redirect(self):
response = self.app.get('/')
self.assertEqual(response.status_code, 302)
def test_get_mobile_index(self):
response = self.app.get('/mobile/index')
self.assertEqual(response.status_code, 200)
def test_get_admin_redirect(self):
response = self.app.get('/admin')
self.assertEqual(response.status_code, 302)
def test_get_content_index(self):
response = self.app.get('/content/title/index')
self.assertEqual(response.status_code, 200)
class HelperTest(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
def test_clip_image(self):
pass
if __name__ == '__main__':
unittest.main()
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,616
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/bb09c512cfd0_create_tracking_info_and_design_application.py
|
"""create_tracking_info_and_design_application
Revision ID: bb09c512cfd0
Revises: a4ef5d3cfd2a
Create Date: 2017-03-04 21:18:09.511320
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'bb09c512cfd0'
down_revision = 'a4ef5d3cfd2a'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('tracking_info',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('contract_no', sa.String(length=50), nullable=True),
sa.Column('contract_date', sa.DateTime(), nullable=True),
sa.Column('receiver_name', sa.String(length=200), nullable=True),
sa.Column('receiver_tel', sa.String(length=30), nullable=True),
sa.Column('production_date', sa.DateTime(), nullable=True),
sa.Column('delivery_date', sa.DateTime(), nullable=True),
sa.Column('delivery_plate_no', sa.String(length=100), nullable=True),
sa.Column('delivery_man_tel', sa.String(length=30), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('design_application',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('filing_no', sa.String(length=50), nullable=True),
sa.Column('status', sa.String(length=50), nullable=True),
sa.Column('ul_file', sa.String(length=200), nullable=True),
sa.Column('dl_file', sa.String(length=200), nullable=True),
sa.Column('applicant_id', sa.Integer(), nullable=True),
sa.Column('operator_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['applicant_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('tracking_info_detail',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=200), nullable=True),
sa.Column('description', sa.String(length=500), nullable=True),
sa.Column('tracking_info_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['tracking_info_id'], ['tracking_info.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('tracking_info_detail')
op.drop_table('design_application')
op.drop_table('tracking_info')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,617
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/b96697ddd85b_.py
|
"""empty message
Revision ID: b96697ddd85b
Revises: cdc933dc3c56
Create Date: 2017-04-01 15:40:44.142760
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b96697ddd85b'
down_revision = 'cdc933dc3c56'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('webpage_describes',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('endpoint', sa.String(length=200), nullable=False),
sa.Column('method', sa.String(length=4), nullable=True),
sa.Column('describe', sa.String(length=200), nullable=False),
sa.Column('validate_flag', sa.Boolean(), nullable=True),
sa.Column('type', sa.String(length=30), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('authority_operations',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('webpage_id', sa.Integer(), nullable=True),
sa.Column('role_id', sa.Integer(), nullable=False),
sa.Column('flag', sa.String(length=10), nullable=True),
sa.Column('remark', sa.String(length=200), nullable=True),
sa.Column('time', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['webpage_id'], ['webpage_describes.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('authority_operations')
op.drop_table('webpage_describes')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,618
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/33f0e654700f_.py
|
"""empty message
Revision ID: 33f0e654700f
Revises: 2d1bf125618d
Create Date: 2017-05-02 14:39:53.742110
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '33f0e654700f'
down_revision = '2d1bf125618d'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('user_infos', 'extra_attributes')
op.add_column('users', sa.Column('extra_attributes', sa.String(length=10), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'extra_attributes')
op.add_column('user_infos', sa.Column('extra_attributes', sa.VARCHAR(length=10), autoincrement=False, nullable=True))
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,619
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/1bbc1621f6d4_add_extra_attributes_to_user_info.py
|
"""add extra_attributes to user_info
Revision ID: 1bbc1621f6d4
Revises: ef83fe89b1ed
Create Date: 2017-04-26 15:00:17.054140
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1bbc1621f6d4'
down_revision = 'ef83fe89b1ed'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('user_infos', sa.Column('extra_attributes', sa.String(length=10), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('user_infos', 'extra_attributes')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,620
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/fc7fc4b255d1_change_production_num_to_float.py
|
"""change production_num to float
Revision ID: fc7fc4b255d1
Revises: 0c39d2c5df1c
Create Date: 2017-05-02 10:27:16.805804
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'fc7fc4b255d1'
down_revision = '0c39d2c5df1c'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('order_contents', 'production_num',
existing_type=sa.INTEGER(),
type_=sa.Float(),
existing_nullable=True)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('order_contents', 'production_num',
existing_type=sa.Float(),
type_=sa.INTEGER(),
existing_nullable=True)
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,621
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/f4c99095e70c_.py
|
"""empty message
Revision ID: f4c99095e70c
Revises: 0c451fc35b86
Create Date: 2017-03-29 10:27:16.400605
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f4c99095e70c'
down_revision = '0c451fc35b86'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('wechat_push_msg',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('wechat_msg_id', sa.String(length=100), nullable=True),
sa.Column('wechat_user_info_id', sa.Integer(), nullable=True),
sa.Column('push_type', sa.String(length=20), nullable=False),
sa.Column('push_info', sa.JSON(), nullable=True),
sa.Column('push_time', sa.DateTime(), nullable=True),
sa.Column('push_flag', sa.Boolean(), nullable=True),
sa.Column('push_remark', sa.String(length=200), nullable=True),
sa.Column('push_times', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['wechat_user_info_id'], ['wechat_user_info.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.alter_column('web_access_log', 'user_agent',
existing_type=sa.VARCHAR(length=200),
type_=sa.String(length=500),
existing_nullable=True)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('web_access_log', 'user_agent',
existing_type=sa.String(length=500),
type_=sa.VARCHAR(length=200),
existing_nullable=True)
op.drop_table('wechat_push_msg')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,622
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/product/forms.py
|
# -*- coding: utf-8 -*-
import wtforms
from wtforms.validators import *
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,623
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/e32af8c8d78a_add_sale_contract_to_order.py
|
"""add sale_contract to order
Revision ID: e32af8c8d78a
Revises: 9fea66319b4a
Create Date: 2017-03-16 21:05:30.065102
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e32af8c8d78a'
down_revision = '9fea66319b4a'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('orders', sa.Column('sale_contract', sa.String(length=200), nullable=True))
op.add_column('orders', sa.Column('sale_contract_id', sa.Integer(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('orders', 'sale_contract_id')
op.drop_column('orders', 'sale_contract')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,624
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/d80a29ceb22a_add_access_token_to_wechat_access_token.py
|
"""add_access_token_to_wechat_access_token
Revision ID: d80a29ceb22a
Revises: 7939e3b94900
Create Date: 2017-03-02 09:54:28.650065
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd80a29ceb22a'
down_revision = '7939e3b94900'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('wechat_access_token', sa.Column('access_token', sa.String(length=500), nullable=False))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('wechat_access_token', 'access_token')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,625
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/8c795821d12d_add_users_and_company_structure_model.py
|
"""add users and company structure model
Revision ID: 8c795821d12d
Revises: 9cc62ef23a49
Create Date: 2017-02-22 08:46:51.672290
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '8c795821d12d'
down_revision = '9cc62ef23a49'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('department_hierarchies',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=300), nullable=False),
sa.Column('parent_id', sa.Integer(), nullable=True),
sa.Column('level_grade', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('resources',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=200), nullable=False),
sa.Column('description', sa.String(length=400), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('sales_area_hierarchies',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=300), nullable=False),
sa.Column('parent_id', sa.Integer(), nullable=True),
sa.Column('level_grade', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('email', sa.String(length=60), nullable=False),
sa.Column('nickname', sa.String(length=200), nullable=True),
sa.Column('user_or_origin', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user_infos',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=400), nullable=True),
sa.Column('telephone', sa.String(length=20), nullable=True),
sa.Column('address', sa.String(length=500), nullable=True),
sa.Column('title', sa.String(length=200), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('users_and_departments',
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('dep_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['dep_id'], ['department_hierarchies.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], )
)
op.create_table('users_and_resources',
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('resource_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['resource_id'], ['resources.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], )
)
op.create_table('users_and_sales_areas',
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('sales_area_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['sales_area_id'], ['sales_area_hierarchies.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], )
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('users_and_sales_areas')
op.drop_table('users_and_resources')
op.drop_table('users_and_departments')
op.drop_table('user_infos')
op.drop_table('users')
op.drop_table('sales_area_hierarchies')
op.drop_table('resources')
op.drop_table('department_hierarchies')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,626
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/product/api.py
|
import requests
from .. import app
site = app.config['PRODUCT_SERVER']
version = 'api_v0.1'
headers = {'Content-Type': 'application/json'}
# resource :products, [:index, :show, :create, :update, :delete]
def load_products(category_id, only_valid=True):
url = '%s/%s/product_category/%s/products' % (site, version, category_id)
response = requests.get(url)
if response.status_code == 200:
return list(filter(lambda x: x.get('isvalid') != 'NO', response.json())) if only_valid is True else response.json()
else:
return []
def load_product(product_id, option_sorted=False):
url = '%s/%s/product/%s' % (site, version, product_id)
response = requests.get(url)
if response.status_code == 200:
product = response.json()
if option_sorted:
options = load_product_options(product.get('product_id')).get('options')
feature_list = []
for option in options:
if not option.get('feature_name') in feature_list:
feature_list.append(option.get('feature_name'))
option_sorted_by_feature = []
for feature in feature_list:
group = []
for option in options:
if option.get('feature_name') == feature:
group.append(option)
option_sorted_by_feature.append(group)
product['option_sorted'] = option_sorted_by_feature
return product
else:
return {}
def create_product(data={}):
url = '%s/%s/products' % (site, version)
response = requests.post(url, json=data, headers=headers)
return response # 201
def update_product(product_id, data):
url = '%s/%s/products/%s/edit' % (site, version, product_id)
response = requests.put(url, json=data, headers=headers)
return response # 200
def delete_product(product_id):
url = '%s/%s/products/%s' % (site, version, product_id)
response = requests.delete(url)
return response
# resource :skus, [:index, :show, :create, :update, :delete]
def load_skus(product_id):
url = '%s/%s/products/%s/skus' % (site, version, product_id)
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return {}
def load_sku(product_id, sku_id):
skus = load_skus(product_id).get('skus')
if skus:
for sku in skus:
if sku.get('sku_id') == sku_id:
return sku
return {}
def create_sku(data={}):
url = '%s/%s/product_skus' % (site, version)
response = requests.post(url, json=data, headers=headers)
return response
def get_sku(sku_id):
url = '%s/%s/product_skus/%s' % (site, version, sku_id)
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return {}
def update_sku(sku_id, data={}):
url = '%s/%s/product_skus/%s/edit' % (site, version, sku_id)
response = requests.put(url, json=data, headers=headers)
return response # 200
def delete_sku(sku_id):
url = '%s/%s/product_skus/%s' % (site, version, sku_id)
response = requests.delete(url)
return response
# resource :categories, [:index, :show, :create, :update]
def load_categories():
url = '%s/%s/product_categories' % (site, version)
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return []
def load_category(category_id):
url = '%s/%s/product_categories/%s' % (site, version, category_id)
response = requests.get(url)
if response.status_code == 200:
return response.json()[0]
else:
return {}
def create_category(data={}):
url = '%s/%s/product_categories' % (site, version)
response = requests.post(url, json=data, headers=headers)
return response # 201
def update_category(category_id, data={}):
url = '%s/%s/product_categories/%s/edit' % (site, version, category_id)
response = requests.put(url, json=data, headers=headers)
return response # 200
# resource :features, [:index, :show, :create, :update]
def load_features():
url = '%s/%s/sku_features' % (site, version)
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return []
def load_feature(feature_id):
url = '%s/%s/sku_feature/%s' % (site, version, feature_id)
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return {}
def create_feature(data={}):
url = '%s/%s/sku_features' % (site, version)
response = requests.post(url, json=data, headers=headers)
return response
def update_feature(feature_id, data={}):
url = '%s/%s/sku_features/%s/edit' % (site, version, feature_id)
response = requests.put(url, json=data, headers=headers)
return response
def delete_feature(feature_id):
url = '%s/%s/sku_feature/%s' % (site, version, feature_id)
response = requests.delete(url)
return response # 200
# resource :options, [:create, :update]
def create_option(data={}):
url = '%s/%s/sku_options' % (site, version)
response = requests.post(url, json=data, headers=headers)
return response
def update_option(option_id, data={}):
url = '%s/%s/sku_options/%s/edit' % (site, version, option_id)
response = requests.put(url, json=data, headers=headers)
return response
def delete_option(option_id):
url = '%s/%s/sku_option/%s' % (site, version, option_id)
response = requests.delete(url)
return response
def load_product_options(product_id):
url = '%s/%s/product/%s/options' % (site, version, product_id)
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return []
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,627
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/cc49d9ce0732_add_pic_files_to_project_report.py
|
"""add pic_files to project report
Revision ID: cc49d9ce0732
Revises: 90b229de33de
Create Date: 2017-04-29 21:39:09.882668
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'cc49d9ce0732'
down_revision = '90b229de33de'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('project_reports', sa.Column('pic_files', sa.JSON(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('project_reports', 'pic_files')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,628
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/c0778ba000bb_add_timestamps_to_project_report.py
|
"""add timestamps to project report
Revision ID: c0778ba000bb
Revises: f5ff15a65fd0
Create Date: 2017-03-06 09:03:15.200570
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c0778ba000bb'
down_revision = 'f5ff15a65fd0'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('project_reports', sa.Column('created_at', sa.DateTime(), nullable=True))
op.add_column('project_reports', sa.Column('updated_at', sa.DateTime(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('project_reports', 'updated_at')
op.drop_column('project_reports', 'created_at')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,629
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/models.py
|
# -*- coding: utf-8 -*-
import datetime
from . import db, login_manager, bcrypt, cache
from flask import url_for
from sqlalchemy import distinct
@login_manager.user_loader
def load_user(user_id):
return User.query.filter_by(id=int(user_id)).first()
class Rails(object):
@property
def save(self):
# 增加rollback防止一个异常导致后续SQL不可使用
try:
db.session.add(self)
db.session.commit()
except Exception as e:
db.session.rollback()
raise e
return self
@property
def delete(self):
db.session.delete(self)
db.session.commit()
return self
# Contents_and_options: id, content_id, content_classification_option_id
contents_and_options = db.Table('contents_and_options',
db.Column('content_id', db.Integer, db.ForeignKey('content.id')),
db.Column('content_classification_option_id', db.Integer,
db.ForeignKey('content_classification_option.id')))
# Contents: id, name,description,content_thumbnail,reference_info(json{name,value})
class Content(db.Model, Rails):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
description = db.Column(db.Text)
image_links = db.Column(db.JSON, default=[])
detail_link = db.Column(db.String(200))
reference_info = db.Column(db.JSON, default={})
product_ids = db.Column(db.JSON, default=[])
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
category_id = db.Column(db.Integer, db.ForeignKey('content_category.id'))
options = db.relationship('ContentClassificationOption', secondary=contents_and_options,
backref=db.backref('contents', lazy='dynamic'), lazy='dynamic')
def __repr__(self):
return 'Content(id: %s, name: %s, ...)' % (self.id, self.name)
def append_options(self, options):
existing_options = self.options
new_options = []
for option in options:
if option not in existing_options:
new_options.append(option)
for option in new_options:
existing_options.append(option)
return self.options
def update_options(self, options):
self.options = []
self.append_options(options)
return self.options
@property
def title_image(self):
if self.image_links:
for image in self.image_links:
if image:
return image
return ''
# Content_categories: id,name
class ContentCategory(db.Model, Rails):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), unique=True)
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
contents = db.relationship('Content', backref='category', lazy='dynamic')
classifications = db.relationship('ContentClassification', backref='category', lazy='dynamic')
def __repr__(self):
return 'ContentCategory(id: %s, name: %s)' % (self.id, self.name)
@property
def delete_p(self):
for classification in self.classifications:
classification.delete_p
self.delete
return self
@property
def options(self):
classification_ids = [classification.id for classification in self.classifications]
options = ContentClassificationOption.query.filter(
ContentClassificationOption.classification_id.in_(classification_ids))
return options
# Content_classifications: id, content_category_id, name,description
class ContentClassification(db.Model, Rails):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
description = db.Column(db.Text)
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
category_id = db.Column(db.Integer, db.ForeignKey('content_category.id'))
options = db.relationship('ContentClassificationOption', backref='classification', lazy='dynamic')
def __repr__(self):
return 'ContentClassification(id: %s, name: %s, description: %s)' % (self.id, self.name, self.description)
@property
def delete_p(self):
for option in self.options:
option.delete
self.delete
return self
# Content_classification_options: id, content_classification_id,name
class ContentClassificationOption(db.Model, Rails):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
classification_id = db.Column(db.Integer, db.ForeignKey('content_classification.id'))
def __repr__(self):
return 'ContentClassificationOption(id: %s, name: %s)' % (self.id, self.name)
class Material(db.Model, Rails):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
memo = db.Column(db.Text)
stock_num = db.Column(db.Integer, default=0)
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
application_contents = db.relationship('MaterialApplicationContent', backref='material', lazy='dynamic')
@property
def used_num(self):
count = 0
application_contents = self.application_contents.join(MaterialApplicationContent.application).filter(
MaterialApplication.status == '同意申请')
for application_content in application_contents:
if application_content.available_number:
count += application_content.available_number
return count
@property
def remain_num(self):
return (self.stock_num or 0) - self.used_num
def __repr__(self):
return 'Material(id: %s, name: %s, ...)' % (self.id, self.name)
class MaterialApplication(db.Model, Rails):
id = db.Column(db.Integer, primary_key=True)
app_no = db.Column(db.String(30), unique=True)
status = db.Column(db.String(50))
app_type = db.Column(db.Integer) # 根据申请人确认申请类型, [3: 'staff', 2: 'dealer']
sales_area = db.Column(db.String(20)) # 销售区域(省份), 用于统计
app_memo = db.Column(db.String(500)) # 物料申请备注
memo = db.Column(db.String(200))
app_infos = db.Column(db.JSON, default={})
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
application_contents = db.relationship('MaterialApplicationContent', backref='application', lazy='dynamic')
def __repr__(self):
return 'MaterialApplication(id: %s, app_no: %s, status: %s, ...)' % (self.id, self.app_no, self.status)
def app_type_desc(self):
if self.app_type == 2:
return '经销商申请'
elif self.app_type == 3:
return '员工申请'
else:
return '未知类型'
class MaterialApplicationContent(db.Model, Rails):
id = db.Column(db.Integer, primary_key=True)
material_id = db.Column(db.Integer, db.ForeignKey('material.id'))
material_name = db.Column(db.String(100))
number = db.Column(db.Integer)
available_number = db.Column(db.Integer)
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
application_id = db.Column(db.Integer, db.ForeignKey('material_application.id'))
def __repr__(self):
return 'MaterialApplicationContent(id: %s, material_id: %s, number: %s,...)' % (
self.id, self.material_id, self.number)
class DesignApplication(db.Model, Rails):
id = db.Column(db.Integer, primary_key=True)
filing_no = db.Column(db.String(50))
status = db.Column(db.String(50))
ul_file = db.Column(db.String(200))
dl_file = db.Column(db.String(200))
dl_file_memo = db.Column(db.String(500))
applicant_id = db.Column(db.Integer, db.ForeignKey('users.id'))
operator_id = db.Column(db.Integer)
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
def __repr__(self):
return 'DesignApplication(id: %s, filing_no: %s, status: %s,...)' % (self.id, self.filing_no, self.status)
class ShareInventory(db.Model, Rails):
id = db.Column(db.Integer, primary_key=True)
applicant_id = db.Column(db.Integer, db.ForeignKey('users.id'))
audit_id = db.Column(db.Integer)
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
status = db.Column(db.String(50))
batch_no = db.Column(db.String(50))
product_name = db.Column(db.String(200))
sku_option = db.Column(db.String(200))
sku_code = db.Column(db.String(30))
sku_id = db.Column(db.Integer)
production_date = db.Column(db.String(30))
stocks = db.Column(db.Float)
price = db.Column(db.Float)
audit_price = db.Column(db.Float)
pic_files = db.Column(db.JSON)
@property
def app_user(self):
return User.query.get_or_404(self.applicant_id)
@property
def sale_director_id(self):
province_id = User.query.get_or_404(self.applicant_id).sales_areas.first().parent_id
region_id = SalesAreaHierarchy.query.get_or_404(province_id).parent_id
us = db.session.query(User).join(User.departments).join(User.sales_areas).filter(
User.user_or_origin == 3).filter(
DepartmentHierarchy.name == "销售部").filter(
SalesAreaHierarchy.id == region_id).first()
if us is not None:
return us.id
else:
return 0
class TrackingInfo(db.Model, Rails):
id = db.Column(db.Integer, primary_key=True)
status = db.Column(db.String(50))
contract_no = db.Column(db.String(50))
contract_date = db.Column(db.DateTime)
receiver_name = db.Column(db.String(200))
receiver_tel = db.Column(db.String(30))
production_date = db.Column(db.DateTime)
production_manager = db.Column(db.String(200))
production_starts_at = db.Column(db.DateTime)
production_ends_at = db.Column(db.DateTime)
delivery_date = db.Column(db.DateTime)
delivery_infos = db.Column(db.JSON, default={})
# logistics_company = db.Column(db.String(200))
# delivery_plate_no = db.Column(db.String(100))
# delivery_man_name = db.Column(db.String(200))
# delivery_man_tel = db.Column(db.String(30))
qrcode_token = db.Column(db.String(128))
qrcode_image = db.Column(db.String(200))
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
details = db.relationship('TrackingInfoDetail', backref='tracking_info', lazy='dynamic')
qrcode_scan_date = db.Column(db.DateTime)
def __repr__(self):
return 'TrackingInfo(id: %s, contract_no: %s,...)' % (self.id, self.contract_no)
@property
def production_status(self):
if self.production_date:
if self.production_date <= datetime.datetime.now():
return '已生产'
return '未生产'
@property
def delivery_status(self):
if self.delivery_date:
if self.delivery_date <= datetime.datetime.now():
return '已发货'
return '未发货'
@property
def qrcode_image_path(self):
if self.qrcode_image:
return '/static/upload/qrcode/%s' % self.qrcode_image
return ''
class TrackingInfoDetail(db.Model, Rails):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200))
description = db.Column(db.String(500))
tracking_info_id = db.Column(db.Integer, db.ForeignKey('tracking_info.id'))
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
# 货运公司信息表
class LogisticsCompanyInfo(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
telephone = db.Column(db.String(50))
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
class Order(db.Model, Rails):
__tablename__ = 'orders'
id = db.Column(db.Integer, primary_key=True)
order_no = db.Column(db.String(30), unique=True)
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
order_status = db.Column(db.String(50))
order_memo = db.Column(db.Text)
buyer_info = db.Column(db.JSON)
sale_contract = db.Column(db.String(200))
sale_contract_id = db.Column(db.Integer)
contracts = db.relationship('Contract', backref='order', lazy='dynamic')
order_contents = db.relationship('OrderContent', backref='order')
def __repr__(self):
return 'Order(id: %s, order_no: %s, user_id: %s, order_status: %s, order_memo: %s)' % (
self.id, self.order_no, self.user_id, self.order_status, self.order_memo)
@property
def sale_director(self):
province_id = User.query.get_or_404(self.user_id).sales_areas.first().parent_id
region_id = SalesAreaHierarchy.query.get_or_404(province_id).parent_id
us = db.session.query(User).join(User.departments).join(User.sales_areas).filter(
User.user_or_origin == 3).filter(
DepartmentHierarchy.name == "销售部").filter(
SalesAreaHierarchy.id == region_id).first()
if us is not None:
return us.nickname
else:
return ''
@property
def sale_director_id(self):
province_id = User.query.get_or_404(self.user_id).sales_areas.first().parent_id
region_id = SalesAreaHierarchy.query.get_or_404(province_id).parent_id
us = db.session.query(User).join(User.departments).join(User.sales_areas).filter(
User.user_or_origin == 3).filter(
DepartmentHierarchy.name == "销售部").filter(
SalesAreaHierarchy.id == region_id).first()
if us is not None:
return us.id
else:
return 0
@property
def sale_contract_phone(self):
return '' if self.sale_contract_id is None else User.query.get(self.sale_contract_id).user_infos[0].telephone
class Contract(db.Model):
__tablename__ = 'contracts'
id = db.Column(db.Integer, primary_key=True)
contract_no = db.Column(db.String(30), unique=True)
contract_date = db.Column(db.DateTime, default=datetime.datetime.now)
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
order_id = db.Column(db.Integer, db.ForeignKey('orders.id'))
contract_status = db.Column(db.String(50))
product_status = db.Column(db.String(50))
shipment_status = db.Column(db.String(50))
payment_status = db.Column(db.String(50), default='未付款')
contract_content = db.Column(db.JSON)
def __repr__(self):
return 'Contract(id: %s, contract_no: %s, contract_date: %s, order_id: %s, contract_status: %s, product_status: %s, shipment_status: %s, ...)' % (
self.id, self.contract_no, self.contract_date, self.order_id, self.contract_status, self.product_status,
self.shipment_status)
@property
def production_status(self):
tracking_info = TrackingInfo.query.filter_by(contract_no=self.contract_no).first()
if tracking_info:
return tracking_info.production_status
return '未生产'
@property
def delivery_status(self):
tracking_info = TrackingInfo.query.filter_by(contract_no=self.contract_no).first()
if tracking_info:
return tracking_info.delivery_status
return '未发货'
class OrderContent(db.Model, Rails):
__tablename__ = 'order_contents'
id = db.Column(db.Integer, primary_key=True)
order_id = db.Column(db.Integer, db.ForeignKey('orders.id'))
product_name = db.Column(db.String(300))
sku_specification = db.Column(db.String(500))
sku_code = db.Column(db.String(30))
number = db.Column(db.Float)
square_num = db.Column(db.Float)
price = db.Column(db.Float, default=0)
amount = db.Column(db.Float, default=0)
memo = db.Column(db.String(100))
batch_info = db.Column(db.JSON, default={})
production_num = db.Column(db.Float, default=0)
inventory_choose = db.Column(db.JSON, default=[])
def __repr__(self):
return 'OrderContent(id: %s, order_id: %s, product_name: %s, sku_specification: %s, sku_code: %s, number: %s, square_num: %s)' % (
self.id, self.order_id, self.product_name, self.sku_specification, self.sku_code, self.number,
self.square_num)
users_and_resources = db.Table(
'users_and_resources',
db.Column('user_id', db.Integer, db.ForeignKey('users.id')),
db.Column('resource_id', db.Integer, db.ForeignKey('resources.id'))
)
users_and_sales_areas = db.Table(
'users_and_sales_areas',
db.Column('user_id', db.Integer, db.ForeignKey('users.id')),
db.Column('sales_area_id', db.Integer, db.ForeignKey('sales_area_hierarchies.id')),
db.Column('parent_id', db.Integer),
db.Column('parent_time', db.DateTime)
)
users_and_departments = db.Table(
'users_and_departments',
db.Column('user_id', db.Integer, db.ForeignKey('users.id')),
db.Column('dep_id', db.Integer, db.ForeignKey('department_hierarchies.id'))
)
class UserAndSaleArea(db.Model, Rails):
__tablename__ = 'users_and_sales_areas'
__table_args__ = {"useexisting": True}
user_id = db.Column('user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True)
sales_area_id = db.Column('sales_area_id', db.Integer, db.ForeignKey('sales_area_hierarchies.id'), primary_key=True)
parent_id = db.Column('parent_id', db.Integer)
parent_time = db.Column('parent_time', db.DateTime)
class User(db.Model, Rails):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
password_hash = db.Column(db.String(100), nullable=False)
email = db.Column(db.String(60), nullable=False, unique=True)
nickname = db.Column(db.String(200))
user_or_origin = db.Column(db.Integer)
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
user_infos = db.relationship('UserInfo', backref='user')
orders = db.relationship('Order', backref='user', lazy='dynamic')
contracts = db.relationship('Contract', backref='user', lazy='dynamic')
material_applications = db.relationship('MaterialApplication', backref='user', lazy='dynamic')
design_applications = db.relationship('DesignApplication', backref='applicant', lazy='dynamic')
resources = db.relationship('Resource', secondary=users_and_resources,
backref=db.backref('users', lazy='dynamic'), lazy='dynamic')
sales_areas = db.relationship('SalesAreaHierarchy', secondary=users_and_sales_areas,
backref=db.backref('users', lazy='dynamic'), lazy='dynamic')
departments = db.relationship('DepartmentHierarchy', secondary=users_and_departments,
backref=db.backref('users', lazy='dynamic'), lazy='dynamic')
# 特殊属性 - 每一位使用0,1作为区分
# 经销商用户 - 首位表示是否加盟 0:未加盟 , 1:加盟
# 是否被禁止登入 - 第2位表示是否被禁止登入 0:未禁止, 1:禁止
# 员工 - 暂未使用此字段
extra_attributes = db.Column(db.String(10), default='')
def __repr__(self):
return '<User %r -- %r>' % (self.id, self.nickname)
# 用户的对象是否可认证 , 因为某些原因不允许被认证
def is_authenticated(self):
return True
# 用户的对象是否有效 , 账号被禁止
def is_active(self):
return True
# 为那些不被获准登录的用户返回True
def is_anonymous(self):
if self.extra_attributes is not None and self.extra_attributes[1:2] == '1':
return True
return False
# 设置用户是否禁用
def set_is_anonymous(self, is_anonymous_data):
if is_anonymous_data is None or is_anonymous_data == 'None':
is_anonymous_data = '0'
if self.extra_attributes is None or self.extra_attributes == "":
# 第一位默认为1
self.extra_attributes = '1' + is_anonymous_data
else:
list_extra_attributes = list(self.extra_attributes)
list_extra_attributes[1] = is_anonymous_data
self.extra_attributes = ''.join(list_extra_attributes)
# 设置用户是否加盟 -- 供应商专属属性
def set_join_dealer(self, join_dealer_data):
if join_dealer_data is None or join_dealer_data == 'None':
join_dealer_data = '1'
if self.user_or_origin == 2:
if self.extra_attributes is None or self.extra_attributes == "":
# 第二位默认为0
self.extra_attributes = join_dealer_data + "0"
else:
list_extra_attributes = list(self.extra_attributes)
list_extra_attributes[0] = join_dealer_data
self.extra_attributes = ''.join(list_extra_attributes)
# 为用户返回唯一的unicode标识符
def get_id(self):
return str(self.id).encode("utf-8")
def check_can_login(self):
if self.user_or_origin == 3 and self.departments.count() == 0:
return "用户[%s]部门异常,请联系管理员" % self.nickname
if self.is_anonymous():
if self.user_or_origin == 2:
return "[%s经销商]暂时无法登陆,请联系管理员" % self.nickname
else:
return "用户[%s]已被禁用,请联系管理员" % self.nickname
return ""
def get_user_type_name(self):
return {2: "经销商", 3: "员工"}[self.user_or_origin]
# 前台查询,新增,修改用户权限控制
def authority_control_to_user(self, other_user):
# 可操作任意经销商
if other_user is None or other_user.user_or_origin == 2:
return None
# 等级权限高 - 董事长
if self.get_max_level_grade() < other_user.get_max_level_grade():
return None
# 所属部门是否有交集
self_d_array = [d.id for d in self.departments.all()]
other_d_array = [d.id for d in other_user.departments.all()]
if list(set(self_d_array).intersection(set(other_d_array))) != []:
return None
return "当前用户[%s] 无权限操作用户[%s]" % (self.nickname, other_user.nickname)
@property
def password(self):
return self.password_hash
@password.setter
def password(self, value):
self.password_hash = bcrypt.generate_password_hash(value).decode('utf-8')
# 获取用户的最大部门等级
def get_max_level_grade(self):
max_level_grade = 99
for d in self.departments:
if max_level_grade > d.level_grade:
max_level_grade = d.level_grade
return max_level_grade
# 授权加载2小时
@cache.memoize(7200)
# 是否有授权
def is_authorized(self, endpoint, method="GET"):
print("User[%s] endpoint[%s] is authorized cache" % (self.nickname, endpoint))
return AuthorityOperation.is_authorized(self, endpoint, method)
# 获取用户所属role -- 暂使用所属部门代替
def get_roles(self):
return [(d.id, d.name) for d in self.departments.order_by(DepartmentHierarchy.id.asc()).all()]
def get_province_sale_areas(self):
if not self.user_or_origin == 3:
return []
if self.departments.filter_by(name="销售部").first() is not None: # 销售部员工
areas = []
for area in self.sales_areas:
if area.level_grade == 2: # 销售总监,管理一个大区
areas += SalesAreaHierarchy.query.filter_by(level_grade=3, parent_id=area.id).all()
elif area.level_grade == 3: # 普通销售人员,管理一个省
areas += [area]
else:
areas += []
return areas
else:
return []
def get_subordinate_dealers(self):
return db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(
SalesAreaHierarchy.level_grade == 4).filter(
SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id.in_([province.id for province in self.get_province_sale_areas()]))])).all()
@property
def is_sales_department(self):
sales_department = DepartmentHierarchy.query.filter_by(name='销售部').first()
if sales_department in self.departments:
return True
else:
return False
@cache.memoize(7200)
def get_orders_num(self):
if self.is_sales_department:
num = Order.query.filter_by(order_status='新订单').filter(
Order.user_id.in_(set([user.id for user in self.get_subordinate_dealers()]))).count()
return num
else:
return 0
def get_other_app_num(self):
return self.get_material_application_num() + self.get_project_report_num() + self.get_share_inventory_num()
@cache.memoize(7200)
def get_material_application_num(self):
if self.is_sales_department:
num = MaterialApplication.query.filter_by(status='新申请').filter(
MaterialApplication.user_id.in_(set([user.id for user in self.get_subordinate_dealers()]))).count()
return num
else:
return 0
@cache.memoize(7200)
def get_material_application_approved_num(self):
return MaterialApplication.query.filter(MaterialApplication.status == '同意申请').count()
@cache.memoize(7200)
def get_project_report_num(self):
if self.is_sales_department:
num = ProjectReport.query.filter_by(status='新创建待审核').filter(
ProjectReport.app_id.in_(set([user.id for user in self.get_subordinate_dealers()]))).count()
return num
else:
return 0
@cache.memoize(7200)
def get_share_inventory_num(self):
if self.is_sales_department:
num = ShareInventory.query.filter_by(status='新申请待审核').filter(
ShareInventory.applicant_id.in_(set([user.id for user in self.get_subordinate_dealers()]))).count()
return num
else:
return 0
# @cache.memoize(7200)
def get_finance_contract_num(self):
return Contract.query.filter(Contract.payment_status == '未付款').count()
def get_contract_for_tracking_num(self):
return Contract.query.filter((Contract.payment_status == '已付款') &
(Contract.shipment_status == '未出库')).count()
# 获取'新申请'产品设计的数量, DesignApplication
@cache.memoize(7200)
def get_new_design_application_num(self):
return DesignApplication.query.filter(DesignApplication.status == '新申请').count()
# 是否为销售总监
# Y - 是 ; N - 否 ; U - 未知
def is_sale_manage(self):
# 存在已有的销售记录
if self.get_sale_manage_provinces():
return "Y"
# 什么记录都没
if self.user_or_origin == 3 and self.departments.filter_by(
name="销售部").first() is not None and self.sales_areas.first() is None:
return "U"
return "N"
# 获取销售总监所管理的大区
def get_sale_manage_provinces(self):
if not self.user_or_origin == 3:
return []
if self.departments.filter_by(name="销售部").first() is None:
return []
return [uasa.sales_area_id for uasa in UserAndSaleArea.query.filter(UserAndSaleArea.user_id == self.id,
UserAndSaleArea.parent_id == None).all()]
# 是否管理某一大区
def is_manage_province(self, sale_area_id):
return sale_area_id in self.get_sale_manage_provinces()
# 是否经销商
def is_dealer(self):
return self.user_or_origin == 2
# 是否员工
def is_staff(self):
return self.user_or_origin == 3
# 是否加盟经销商
def is_join_dealer(self):
return self.user_or_origin == 2 and \
self.extra_attributes is not None and \
self.extra_attributes[0:1] == "1"
# 根据email+密码获取用户实例
@classmethod
def login_verification(cls, email, password, user_or_origin):
user = User.query.filter(User.email == email)
if user_or_origin:
user = user.filter(User.user_or_origin == user_or_origin)
user = user.first()
if user is not None:
if not bcrypt.check_password_hash(user.password, password):
user = None
return user
# 验证并修改用户密码
@classmethod
def update_password(cls, email, password_now, password_new, password_new_confirm, user_or_origin):
user = User.login_verification(email, password_now, user_or_origin)
if user is None:
raise ValueError("密码错误")
if password_now == password_new:
raise ValueError("新旧密码不可相同")
if password_new != password_new_confirm:
raise ValueError("新密码两次输入不匹配")
if len(password_new) < 8 or len(password_new) > 20:
raise ValueError("密码长度必须大等于8小等于20")
user.password = password_new
user.save
# 获取所有role -- 暂使用所属部门代替
@classmethod
def get_all_roles(cls):
return [(d.id, d.name) for d in DepartmentHierarchy.query.order_by(DepartmentHierarchy.id.asc()).all()]
class UserInfo(db.Model):
__tablename__ = 'user_infos'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(400))
telephone = db.Column(db.String(20))
address = db.Column(db.String(500))
title = db.Column(db.String(200))
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
def __repr__(self):
return '<UserInfo %r -- %r>' % (self.id, self.name)
class Resource(db.Model):
__tablename__ = 'resources'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200), nullable=False)
description = db.Column(db.String(400))
class SalesAreaHierarchy(db.Model):
__tablename__ = 'sales_area_hierarchies'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(300), nullable=False)
parent_id = db.Column(db.Integer)
level_grade = db.Column(db.Integer)
def __repr__(self):
# return 'SalesAreaHierarchy %r' % self.name
return '<SalesAreaHierarchy %r -- %r>' % (self.id, self.name)
@classmethod
def get_team_info_by_regional(cls, regional_id):
regional_province = {}
for regional_info in SalesAreaHierarchy.query.filter_by(parent_id=regional_id).all():
# 每个省份只有一个销售员
team = ()
team_info = UserAndSaleArea.query.filter(UserAndSaleArea.parent_id != None,
UserAndSaleArea.sales_area_id == regional_info.id).first()
if team_info is None:
team = (-1, "无")
else:
u = User.query.filter(User.id == team_info.user_id).first()
team = (u.id, u.nickname)
regional_province[regional_info.id] = {"regional_province_name": regional_info.name, "team_info": team}
if regional_province == {}:
regional_province[-1] = {"regional_province_name": "无", "team_info": (-1, "无")}
return regional_province
class DepartmentHierarchy(db.Model):
__tablename__ = 'department_hierarchies'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(300), nullable=False)
parent_id = db.Column(db.Integer)
level_grade = db.Column(db.Integer)
def __repr__(self):
return '<DepartmentHierarchy %r -- %r>' % (self.id, self.name)
class ProjectReport(db.Model):
__tablename__ = 'project_reports'
id = db.Column(db.Integer, primary_key=True)
app_id = db.Column(db.Integer)
audit_id = db.Column(db.Integer)
report_no = db.Column(db.String(50))
status = db.Column(db.String(50))
report_content = db.Column(db.JSON, default={})
audit_content = db.Column(db.JSON, default={})
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
pic_files = db.Column(db.JSON)
@property
def app_name(self):
return User.query.get_or_404(self.app_id).nickname
@property
def sale_director_id(self):
province_id = User.query.get_or_404(self.app_id).sales_areas.first().parent_id
region_id = SalesAreaHierarchy.query.get_or_404(province_id).parent_id
us = db.session.query(User).join(User.departments).join(User.sales_areas).filter(
User.user_or_origin == 3).filter(
DepartmentHierarchy.name == "销售部").filter(
SalesAreaHierarchy.id == region_id).first()
if us is not None:
return us.id
else:
return 0
# 页面说明表
class WebpageDescribe(db.Model, Rails):
__tablename__ = 'webpage_describes'
id = db.Column(db.Integer, primary_key=True)
endpoint = db.Column(db.String(200), nullable=False)
method = db.Column(db.String(4), default="GET") # GET or POST
describe = db.Column(db.String(200), nullable=False)
validate_flag = db.Column(db.Boolean, default=True) # 是否需要校验权限
type = db.Column(db.String(30), default="pc_sidebar") # 页面类型
authority_operations = db.relationship('AuthorityOperation', backref='web_describe', lazy='dynamic')
def __repr__(self):
return '<WebpageDescribe %r -- %r,%r>' % (self.id, self.endpoint, self.describe)
@classmethod
def get_all_types(cls):
return [(web_type[0], web_type[0]) for web_type in db.session.query(distinct(WebpageDescribe.type)).all()]
# 校验endpoint是否合法等
def check_data(self):
if self.method is not None and self.method not in ["GET", "POST"]:
raise "method wrong"
# 无对应数据,会抛出异常
url_for(self.endpoint)
# endpoint + method 唯一数据
if WebpageDescribe.query.filter_by(endpoint=self.endpoint, method=(self.method or "GET")).first() is not None:
raise "has exists record"
# 页面操作权限表
class AuthorityOperation(db.Model, Rails):
__tablename__ = 'authority_operations'
id = db.Column(db.Integer, primary_key=True)
webpage_id = db.Column(db.Integer, db.ForeignKey('webpage_describes.id'))
role_id = db.Column(db.Integer, nullable=False) # 暂时对应DepartmentHierarchy.id
flag = db.Column(db.String(10)) # 权限配置是否有效等
remark = db.Column(db.String(200)) # 权限备注
time = db.Column(db.DateTime, default=datetime.datetime.now) # 权限设置时间
def __repr__(self):
return '<AuthorityOperation %r -- %r,%r>' % (self.id, self.webpage_id, self.role_id)
# role_id获取对应中文
def get_role_name(self):
return DepartmentHierarchy.query.filter_by(id=self.role_id).first().name
@classmethod
def is_authorized(cls, user, endpoint, method="GET"):
if user is None or endpoint is None:
raise "is_authorized params wrong:[user,endpoint,method]"
wd = WebpageDescribe.query.filter_by(endpoint=endpoint, method=method).first()
# 无配置数据 默认有访问权限
if wd is None or wd.validate_flag is False:
return True
auth_flag = False
for (role_id, role_name) in user.get_roles():
ao = cls.query.filter_by(role_id=role_id, webpage_id=wd.id).first()
if ao is None or ao.flag != "Y":
continue
auth_flag = True
break
return auth_flag
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,630
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/c6fb90a99137_add_batch_info_to_order_content.py
|
"""add batch info to order_content
Revision ID: c6fb90a99137
Revises: 483fbd912e83
Create Date: 2017-03-23 16:44:57.607788
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c6fb90a99137'
down_revision = '483fbd912e83'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('order_contents', sa.Column('batch_info', sa.JSON(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('order_contents', 'batch_info')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,631
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/inventory/api.py
|
import requests
from .. import app
site = app.config['PRODUCT_SERVER']
version = 'api_v0.1'
headers = {'Content-Type': 'application/json'}
def load_categories():
url = '%s/%s/product_categories' % (site, version)
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return []
def load_products(category_id):
url = '%s/%s/product_category/%s/products' % (site, version, category_id)
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return []
def load_skus(product_id):
url = '%s/%s/products/%s/skus' % (site, version, product_id)
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return {}
def create_inventory(data={}):
url = '%s/%s/inventories' % (site, version)
response = requests.post(url, json=data, headers=headers)
return response # 201
def load_inventories(sku_id):
url = '%s/%s/sku/%s/inventories' % (site, version, sku_id)
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return []
def load_inventories_by_code(code):
url = '%s/%s/sku/%s/inventories_by_code' % (site, version, code)
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return []
def update_inventory(inv_id, data={}):
url = '%s/%s/inventories/%s/edit' % (site, version, inv_id)
response = requests.put(url, json=data, headers=headers)
return response # 200
def delete_inventory(inv_id):
url = '%s/%s/inventories/%s' % (site, version, inv_id)
response = requests.delete(url)
return response # 200
def load_inventory(inv_id):
url = '%s/%s/inventories/%s' % (site, version, inv_id)
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return {}
def update_sku(sku_id, data={}):
url = '%s/%s/product_skus/%s/edit' % (site, version, sku_id)
response = requests.put(url, json=data, headers=headers)
return response # 200
def update_sku_by_code(data={}):
url = '%s/%s/product_skus/edit_by_code' % (site, version)
response = requests.put(url, json=data, headers=headers)
return response # 200
def load_all_skus(data={}):
url = '%s/%s/product_skus/search' % (site, version)
response = requests.post(url, json=data, headers=headers)
return response.json() # 200
def load_skufeatures():
url = '%s/%s/sku_features' % (site, version)
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return []
def load_users_inventories(data={}):
url = '%s/%s/sku/users_inventories' % (site, version)
response = requests.post(url, json=data, headers=headers)
return response.json()
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,632
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/organization/forms.py
|
from wtforms import Form, StringField, TextAreaField, SelectField, PasswordField, validators, SelectMultipleField, \
SubmitField
from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField
from flask_login import current_user
from ..models import SalesAreaHierarchy, DepartmentHierarchy, User, WebpageDescribe
from ..forms import BaseCsrfForm
def valid_sale_range(form, field):
if form.user_type.data == "2" and field.data is None:
raise validators.ValidationError('请选择销售范围')
def valid_dept_ranges(form, field):
if form.user_type.data == "3" and field.data == []:
raise validators.ValidationError('请选择所属部门')
def get_dynamic_sale_range_query(level_grade, parent_id=None):
sahs = SalesAreaHierarchy.query.filter(SalesAreaHierarchy.level_grade == level_grade)
if parent_id is not None:
sahs = sahs.filter_by(parent_id=parent_id)
return sahs.order_by(SalesAreaHierarchy.id).all()
def get_dynamic_dept_ranges_query():
dhs = DepartmentHierarchy.query
# 前端已进行控制,防止异常增加逻辑
if current_user is None or not current_user.is_authenticated or current_user.departments.count() == 0:
return dhs.order_by(DepartmentHierarchy.id).all()
max_depart_level = current_user.get_max_level_grade()
dhs = dhs.filter(DepartmentHierarchy.level_grade > max_depart_level)
dhs = dhs.union(current_user.departments)
return dhs.order_by(DepartmentHierarchy.id).all()
class BaseForm(Form):
def reset_select_field(self):
self.dept_ranges.query = get_dynamic_dept_ranges_query()
self.sale_range_province.query = get_dynamic_sale_range_query(3)
self.sale_range.query = get_dynamic_sale_range_query(4)
@classmethod
def get_sale_range_by_parent(cls, level_grade, parent_id):
return get_dynamic_sale_range_query(level_grade, parent_id)
# BASE USER
class UserForm(BaseForm, BaseCsrfForm):
email = StringField('邮箱', [validators.Email(message="请填写正确格式的email")])
name = StringField('姓名', [validators.Length(min=2, max=30, message="字段长度必须大等于2小等于30")])
nickname = StringField('昵称', [validators.Length(min=2, max=30, message="字段长度必须大等于2小等于30")])
password = PasswordField('密码', validators=[
validators.DataRequired(message="字段不可为空"),
validators.Length(min=8, max=20, message="字段长度必须大等于8小等于20"),
validators.EqualTo('password_confirm', message="两次输入密码不匹配")
])
password_confirm = PasswordField('密码')
address = TextAreaField('地址', [validators.Length(min=5, max=300, message="字段长度必须大等于5小等于300")])
# 电话匹配规则 11位手机 or 3-4区号(可选)+7-8位固话+1-6分机号(可选)
phone = StringField('电话',
[validators.Regexp(r'(^\d{11})$|(^(\d{3,4}-)?\d{7,8}(-\d{1,5})?$)', message="请输入正确格式的电话")])
title = StringField('头衔')
user_type = SelectField('用户类型', choices=[('3', '员工'), ('2', '经销商')],
validators=[validators.DataRequired(message="字段不可为空")])
# dept_ranges = SelectMultipleField('dept_ranges',choices=[ ('-1','选择所属部门')] + [(str(dh.id),dh.name) for dh in DepartmentHierarchy.query.all() ])
# sale_range = SelectField('sale_range',choices=[ ('-1','选择销售范围')] + [(str(sah.id),sah.name) for sah in SalesAreaHierarchy.query.filter_by(level_grade=4).all() ])
dept_ranges = QuerySelectMultipleField(u'所属部门', get_label="name", validators=[valid_dept_ranges])
sale_range_province = QuerySelectField(u'销售范围(省)', get_label="name", allow_blank=True)
sale_range = QuerySelectField(u'销售范围', get_label="name", allow_blank=True, validators=[valid_sale_range])
join_dealer = SelectField(u'是否加盟', coerce=int, choices=[(1, '是'), (0, '否')])
is_anonymous = SelectField('是否禁用', coerce=int, choices=[(1, '是'), (0, '否')])
# BASE USER_SEARCH
class UserSearchForm(BaseForm):
email = StringField('邮箱')
name = StringField('姓名')
user_type = SelectField('用户类型', choices=[(3, '员工'), (2, '经销商')],
validators=[validators.DataRequired(message="字段不可为空")])
# dept_ranges = SelectMultipleField('dept_ranges',choices=[ (-1,'选择所属部门')] + [(str(dh.id),dh.name) for dh in DepartmentHierarchy.query.all() ])
# sale_range = SelectField('sale_range',choices=[ (-1,'选择销售范围')] + [(str(sah.id),sah.name) for sah in SalesAreaHierarchy.query.filter_by(level_grade=3).all() ])
dept_ranges = QuerySelectMultipleField(u'所属部门', get_label="name")
sale_range_province = QuerySelectField(u'销售范围(省)', get_label="name", allow_blank=True)
sale_range = QuerySelectField(u'销售范围', get_label="name", allow_blank=True)
class RegionalSearchForm(Form):
regional = QuerySelectMultipleField(u'区域', get_label="name")
def reset_select_field(self):
self.regional.query = get_dynamic_sale_range_query(2)
class AuthoritySearchForm(BaseCsrfForm):
roles = SelectMultipleField('角色', choices=[('', '全部')] + User.get_all_roles())
web_types = SelectMultipleField('页面类型', choices=WebpageDescribe.get_all_types())
describe = StringField('页面描述')
submit = SubmitField('筛选条件')
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,633
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/e956ef9ac5fc_add_app_type_to_material_application.py
|
"""add_app_type_to_material_application
Revision ID: e956ef9ac5fc
Revises: 30bb070970b9
Create Date: 2017-05-14 12:29:52.839022
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e956ef9ac5fc'
down_revision = '30bb070970b9'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('material_application', sa.Column('app_infos', sa.JSON(), nullable=True))
op.add_column('material_application', sa.Column('app_type', sa.Integer(), nullable=True))
op.add_column('material_application', sa.Column('sales_area', sa.String(length=20), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('material_application', 'sales_area')
op.drop_column('material_application', 'app_type')
op.drop_column('material_application', 'app_infos')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,634
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/backstage_management/views.py
|
from flask import Blueprint, flash, redirect, render_template, request, url_for, session
from .. import app
from ..models import User, AuthorityOperation, WebpageDescribe
from .forms import AccountLoginForm, AccountForm
from ..forms import BaseCsrfForm
from flask_login import logout_user, login_user, current_user
from ..wechat.models import WechatCall, WechatUserInfo
backstage_management = Blueprint('backstage_management', __name__, template_folder='templates')
# 单个使用@login_required
# 访问页面是否登入拦截
@backstage_management.before_app_request
def login_check():
# url_rule
# app.logger.info("into login_check")
# 图片加载 or 无匹配请求
if request.endpoint == "static" or request.endpoint is None:
if request.endpoint is None:
app.logger.info("LOGIN_CHECK None? request.path [%s] , [%s]" % (request.path, request.endpoint))
pass
# 网站root访问 移动端
# 所有移动端页面
# wechat.mobile_ 使用微信相关JS的移动端页面
else:
if request.endpoint == "root" or \
request.endpoint.startswith("mobile_") or \
request.endpoint.startswith("wechat.mobile_") or \
request.path.startswith("/mobile/"):
# 微信自动登入拦截 -- code只能使用一次,所以绑定界面不能拦截
if not request.endpoint == 'wechat.mobile_user_binding' and request.args.get("code") is not None:
app.logger.info("微信端code自动登入拦截 code[%s]" % request.args.get("code"))
try:
openid = WechatCall.get_open_id_by_code(request.args.get("code"))
app.logger.info("微信端code自动登入拦截 openid[%s]" % openid)
wui = WechatUserInfo.query.filter_by(open_id=openid, is_active=True).first()
app.logger.info("微信端code自动登入拦截 wui记录[%s]" % wui)
if wui is not None:
exists_binding_user = User.query.filter_by(id=wui.user_id).first()
app.logger.info("微信端code自动登入拦截 user记录[%s]" % exists_binding_user)
if exists_binding_user is not None:
if current_user.is_authenticated and not exists_binding_user == current_user:
app.logger.info(
"微信自动登入用户[%s],登出[%s]" % (exists_binding_user.nickname, current_user.nickname))
logout_user()
login_user(exists_binding_user)
app.logger.info("binding user login [%s] - [%s]" % (openid, exists_binding_user.nickname))
except Exception as e:
app.logger.info("微信端code自动登入拦截异常[%s]" % e)
pass
# 访问请求端的页面 不进行拦截
if request.endpoint == "mobile_user_login" or request.endpoint == 'wechat.mobile_user_binding':
pass
# 未登入用户跳转登入界面
elif not current_user.is_authenticated:
app.logger.info("LOGIN_CHECK INTO MOBILE request.path [%s] , [%s]" % (request.path, request.endpoint))
# 后端界面
flash("请登入后操作")
session["login_next_url"] = request.path
return redirect(url_for('mobile_user_login'))
# 被禁止用户
else:
login_valid_errmsg = current_user.check_can_login()
if not login_valid_errmsg == "":
flash(login_valid_errmsg)
logout_user()
return redirect(url_for('mobile_user_login'))
# 其他与微信服务器交互接口 不进行登入判断
elif request.endpoint.startswith("wechat."):
# 微信
pass
# 后端管理界面
else:
# 访问请求端的页面 不进行拦截
if request.endpoint == "backstage_management.account_login":
# 后端登入界面
pass
# 未登入用户跳转登入界面
elif not current_user.is_authenticated or current_user.user_or_origin != 3:
app.logger.info("LOGIN_CHECK INTO BACK END request.path [%s] , [%s]" % (request.path, request.endpoint))
# 后端界面
flash("请登入后操作")
session["login_next_url"] = request.path
return redirect(url_for('backstage_management.account_login'))
# 被禁止用户
else:
login_valid_errmsg = current_user.check_can_login()
if not login_valid_errmsg == "":
flash(login_valid_errmsg)
logout_user()
return redirect(url_for('backstage_management.account_login'))
return None
# 访问页面 是否有权限拦截
@backstage_management.before_app_request
def authority_check():
# app.logger.info("into authority_check")
if request.endpoint == "static" or request.endpoint is None \
or current_user is None or not current_user.is_authenticated:
pass
else:
if AuthorityOperation.is_authorized(current_user, request.endpoint, request.method) is False:
flash("无权限登入页面 [%s] ,请确认" % WebpageDescribe.query.filter_by(endpoint=request.endpoint,
method=request.method).first().describe)
return redirect(url_for('backstage_management.index'))
@backstage_management.route('/index')
def index():
app.logger.info("into index")
form = AccountForm(obj=current_user, user_type=current_user.get_user_type_name(), meta={'csrf_context': session})
if len(current_user.user_infos) == 0:
pass
else:
ui = current_user.user_infos[0]
form.name.data = ui.name
form.address.data = ui.address
form.phone.data = ui.telephone
form.title.data = ui.title
if current_user.sales_areas.first() is not None:
form.sale_range.data = ",".join([s.name for s in current_user.sales_areas.all()])
if current_user.departments.first() is not None:
form.dept_ranges.data = ",".join([d.name for d in current_user.departments.all()])
return render_template('backstage_management/index.html', form=form)
# -- login
# 需要区分pc or wechat ?
@backstage_management.route('/account/login', methods=['GET', 'POST'])
def account_login():
if current_user.is_authenticated:
if current_user.user_or_origin == 3:
return redirect(url_for('backstage_management.index'))
else:
# 不运行前后端同时登入在一个WEB上
app.logger.info("移动端用户[%s]自动登出,[%s][%s]" % (current_user.nickname, request.path, request.endpoint))
logout_user()
# app.logger.info("account_login [%s]" % request.args)
if request.method == 'POST':
try:
form = AccountLoginForm(request.form, meta={'csrf_context': session})
if form.validate() is False:
raise ValueError(form.errors)
# 后台只能员工登入
user = User.login_verification(form.email.data, form.password.data, 3)
if user is None:
raise ValueError("用户名或密码错误")
login_valid_errmsg = user.check_can_login()
if not login_valid_errmsg == "":
raise ValueError(login_valid_errmsg)
login_user(user, form.remember_me.data)
app.logger.info("后端用户[%s][%s]登入成功" % (user.email, user.nickname))
# 直接跳转至需访问页面
if session.get("login_next_url"):
next_url = session.pop("login_next_url")
else:
next_url = url_for('backstage_management.index')
return redirect(next_url)
except Exception as e:
app.logger.info("后端用户登入失败[%s]" % e)
flash(e)
else:
form = AccountLoginForm(meta={'csrf_context': session})
return render_template('backstage_management/account_login.html', form=form)
@backstage_management.route('/account/logout')
def account_logout():
logout_user()
return redirect(url_for('backstage_management.account_login'))
# 帐号信息管理
@backstage_management.route('/account/index')
def account_index():
app.logger.info("into account_index")
form = AccountForm(obj=current_user, user_type=current_user.get_user_type_name(), meta={'csrf_context': session})
if len(current_user.user_infos) == 0:
pass
else:
ui = current_user.user_infos[0]
form.name.data = ui.name
form.address.data = ui.address
form.phone.data = ui.telephone
form.title.data = ui.title
if current_user.sales_areas.first() is not None:
form.sale_range.data = ",".join([s.name for s in current_user.sales_areas.all()])
if current_user.departments.first() is not None:
form.dept_ranges.data = ",".join([d.name for d in current_user.departments.all()])
return render_template('backstage_management/account_index.html', form=form)
# 帐号信息管理
@backstage_management.route('/account/password_update', methods=['POST'])
def account_password_update():
app.logger.info("into account_password_update")
try:
form = BaseCsrfForm(request.form, meta={'csrf_context': session})
if form.validate() is False:
raise ValueError("非法提交,请通过正常页面进行修改")
if request.form.get("email") != current_user.email:
raise ValueError("非法提交,请通过正常页面进行修改")
User.update_password(request.form.get("email"),
request.form.get("password_now"),
request.form.get("password_new"),
request.form.get("password_new_confirm"),
current_user.user_or_origin)
flash("密码修改成功")
except Exception as e:
flash("密码修改失败: %s" % e)
return redirect(url_for('backstage_management.account_index'))
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,635
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/636191448952_add_audit_price_to_share_inventory.py
|
"""add audit price to share inventory
Revision ID: 636191448952
Revises: 0c451fc35b86
Create Date: 2017-03-29 11:04:56.305056
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '636191448952'
down_revision = '0c451fc35b86'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('share_inventory', sa.Column('audit_price', sa.Float(), nullable=True))
op.alter_column('web_access_log', 'user_agent',
existing_type=sa.VARCHAR(length=200),
type_=sa.String(length=500),
existing_nullable=True)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('web_access_log', 'user_agent',
existing_type=sa.String(length=500),
type_=sa.VARCHAR(length=200),
existing_nullable=True)
op.drop_column('share_inventory', 'audit_price')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,636
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/c2024ad11427_add_user_id_to_contracts.py
|
"""add_user_id_to_contracts
Revision ID: c2024ad11427
Revises: 131e90437d13
Create Date: 2017-03-09 16:22:03.810885
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c2024ad11427'
down_revision = '131e90437d13'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('contracts', sa.Column('user_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'contracts', 'users', ['user_id'], ['id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'contracts', type_='foreignkey')
op.drop_column('contracts', 'user_id')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,637
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/manage.py
|
# -*- coding: utf-8 -*-
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell
from application import app, db
from application.models import *
from application.wechat.models import *
from application.web_access_log.models import WebAccessLog
import application.views
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
def make_shell_context():
return dict(app=app, db=db, Content=Content, ContentCategory=ContentCategory,
ContentClassification=ContentClassification,
ContentClassificationOption=ContentClassificationOption,
Material=Material, MaterialApplication=MaterialApplication,
MaterialApplicationContent=MaterialApplicationContent, DesignApplication=DesignApplication,
TrackingInfo=TrackingInfo, TrackingInfoDetail=TrackingInfoDetail,
LogisticsCompanyInfo=LogisticsCompanyInfo,
Order=Order, OrderContent=OrderContent, Contract=Contract,
User=User, UserInfo=UserInfo, Resource=Resource, SalesAreaHierarchy=SalesAreaHierarchy,
DepartmentHierarchy=DepartmentHierarchy, UserAndSaleArea=UserAndSaleArea,
WechatAccessToken=WechatAccessToken, WechatCall=WechatCall, WechatUserInfo=WechatUserInfo,
WechatPushMsg=WechatPushMsg,
ProjectReport=ProjectReport, WebAccessLog=WebAccessLog, ShareInventory=ShareInventory,
WebpageDescribe=WebpageDescribe, AuthorityOperation=AuthorityOperation)
manager.add_command("shell", Shell(make_context=make_shell_context))
# 微信token定时检测任务
@manager.command
def cron_wechat_token():
WechatAccessToken.cron_create_token()
@manager.command
def test():
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == '__main__':
manager.run()
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,638
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/65376f05aa12_create_material_application_models.py
|
"""create_material_application_models
Revision ID: 65376f05aa12
Revises: ad50d4738049
Create Date: 2017-02-23 17:31:22.398052
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '65376f05aa12'
down_revision = 'ad50d4738049'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('material',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=True),
sa.Column('memo', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.add_column('material_application_content', sa.Column('material_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'material_application_content', 'material', ['material_id'], ['id'])
op.drop_column('material_application_content', 'name')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('material_application_content', sa.Column('name', sa.VARCHAR(length=100), autoincrement=False, nullable=True))
op.drop_constraint(None, 'material_application_content', type_='foreignkey')
op.drop_column('material_application_content', 'material_id')
op.drop_table('material')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,644
|
whisperity/sync-repositories
|
refs/heads/master
|
/sync_repositories/repository/__init__.py
|
import os
from .repository import Repository
def get_repositories(root):
"""
Walk the directory tree at `root`, and produce `Repository` instances for
found and known repositories.
"""
for cwd, dirs, _ in os.walk(root):
for subdir in map(lambda dir: os.path.join(cwd, dir), dirs):
if subdir.endswith('.svn'):
from .subversion import Subversion
yield Subversion(cwd, subdir)
elif subdir.endswith('.git'):
from .git import Git
if os.path.isdir(subdir) and os.path.islink(subdir):
# If the `.git` "folder" is a symbolic link, the current
# folder is for a Git clone that has its data storage
# offset, such as a submodule.
print("%s symbolic link - skipping \"submodules\" for now"
% subdir)
elif os.path.isdir(subdir):
yield Git(cwd, subdir)
|
{"/sync_repositories/repository/__init__.py": ["/sync_repositories/repository/repository.py", "/sync_repositories/repository/subversion.py", "/sync_repositories/repository/git.py"], "/sync_repositories/repository/subversion.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/credentials/auto_askpass.py": ["/sync_repositories/credentials/__init__.py"], "/sync_repositories/repository/git.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/__main__.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/__init__.py"]}
|
21,645
|
whisperity/sync-repositories
|
refs/heads/master
|
/sync_repositories/credentials/__init__.py
|
from enum import Enum
class Backends(Enum):
KEYRING = 1,
SSH_AGENT = 2
|
{"/sync_repositories/repository/__init__.py": ["/sync_repositories/repository/repository.py", "/sync_repositories/repository/subversion.py", "/sync_repositories/repository/git.py"], "/sync_repositories/repository/subversion.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/credentials/auto_askpass.py": ["/sync_repositories/credentials/__init__.py"], "/sync_repositories/repository/git.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/__main__.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/__init__.py"]}
|
21,646
|
whisperity/sync-repositories
|
refs/heads/master
|
/sync_repositories/repository/subversion.py
|
from copy import deepcopy
import subprocess
import sys
import urllib.parse
try:
import svn.local
except ImportError:
print("Error! `svn` Python package is a dependency, please install.",
file=sys.stderr)
raise
from sync_repositories.credentials import Backends
from .repository import AuthenticationRequirementChecker, Repository, Updater
class Subversion(Repository):
class UsernamePasswordAuthenticationChecker(
AuthenticationRequirementChecker):
"""
Checks whether the given SVN repository needs authentication.
"""
def __init__(self, repository, username=None, password=None):
super().__init__(repository)
if username is None and password is None:
self._credentials = False
elif username is not None and password is not None:
self._credentials = True
else:
raise ValueError("Authentication check for SVN repositories "
"with either both username and password, or "
"none of it.")
self._username = username
self._password = password
def _fun(self):
# The "non-interactive" stops the called SVN binary from asking
# authentication details and turns it into a hard fail.
command = ['svn', 'log', '--limit', str(1),
'--no-auth-cache', '--non-interactive']
original_command = command
if self._credentials:
command.append('--username')
command.append(self._username)
# Make sure we don't leak the password.
original_command = deepcopy(command)
command.append('--password')
command.append(self._password)
try:
subprocess.run(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding='utf-8',
cwd=self._repository.path,
check=True)
return False
except subprocess.CalledProcessError as cpe:
if "Authentication failed" in cpe.output:
return True
raise subprocess.CalledProcessError(cpe.returncode,
original_command,
cpe.output,
cpe.stderr)
def check(self):
return self._fun()
def check_credentials(self):
if not self._credentials:
raise NotImplementedError()
# Need to invert the result here, because _fun() returns whether
# authentication is needed. If credentials are supplied, then the
# method will return False (as in "no authentication needed").
# (Same result happens if the credentials are invalid on a server
# that doesn't need them.)
return not self._fun()
class UsernamePasswordUpdater(Updater):
"""
Updates a Subversion repository working copy with optionally providing
username and password authentication to the server.
"""
def __init__(self, repository, username=None, password=None):
super().__init__(repository)
if username is None and password is None:
self._credentials = False
elif username is not None and password is not None:
self._credentials = True
else:
raise ValueError(
"Call update() for SVN repositories with either "
"both username and password, or none of it.")
self._username = username
self._password = password
def update(self):
command = ['svn', 'update',
'--no-auth-cache', '--non-interactive']
original_command = command
if self._credentials:
command.append('--username')
command.append(self._username)
# Make sure we don't leak the password.
original_command = deepcopy(command)
command.append('--password')
command.append(self._password)
# Create the updater process.
path = self._repository.path
try:
print("Updating '%s'..." % path)
proc = subprocess.run(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding='utf-8',
cwd=path,
check=True)
print(proc.stdout)
return True
except subprocess.CalledProcessError as cpe:
try:
# Raise an exception in which the password isn't shown.
raise subprocess.CalledProcessError(cpe.returncode,
original_command,
cpe.output,
cpe.stderr)
except subprocess.CalledProcessError as cpe2:
print("Update failed for '%s':" % path, file=sys.stderr)
print(cpe2.output, file=sys.stderr)
print(str(cpe2), file=sys.stderr)
return False
def __init__(self, path, datadir):
super().__init__(path, datadir, 'svn')
# Fetch the remote URL for the repository.
try:
repo = svn.local.LocalClient(path)
# from pprint import pprint
# pprint(repo.info())
self.urls = [('root', repo.info()['repository/root'])]
except (OSError, AttributeError):
print("Error! The repository could not be understood by 'svn' "
"Python wrapper...", file=sys.stderr)
raise
def get_authentication_method(self, remote):
# If SVN repositories authenticate, they only authenticate with
# username-password combination.
return Backends.KEYRING
def get_remote_objname(self, remote):
# Use the repository's path under the server as the "object name".
return urllib.parse.urlparse(self.urls[0][1]).path
def get_auth_requirement_detector_for(self, remote):
def _factory(username=None, password=None):
return Subversion.UsernamePasswordAuthenticationChecker(self,
username,
password)
return _factory
def get_updater_for(self, remote):
def _factory(username, password):
return Subversion.UsernamePasswordUpdater(self, username, password)
return _factory
|
{"/sync_repositories/repository/__init__.py": ["/sync_repositories/repository/repository.py", "/sync_repositories/repository/subversion.py", "/sync_repositories/repository/git.py"], "/sync_repositories/repository/subversion.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/credentials/auto_askpass.py": ["/sync_repositories/credentials/__init__.py"], "/sync_repositories/repository/git.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/__main__.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/__init__.py"]}
|
21,647
|
whisperity/sync-repositories
|
refs/heads/master
|
/sync_repositories/credentials/keyring.py
|
import getpass
import sys
try:
import secretstorage
except ImportError:
print("Error! `secretstorage` is a dependency, please install.",
file=sys.stderr)
raise
class SecretStorage():
def __init__(self, bus, collection):
self._bus = bus
self._collection = collection
if self._collection.is_locked():
raise AttributeError("Cannot initialise a keyring from a locked "
"storage.")
@classmethod
def get_storage(cls):
"""
User-facing factory method that creates the `SecretStorage` for the
default secure secret backend.
"""
bus = secretstorage.dbus_init()
def_collection = secretstorage.get_default_collection(bus)
if def_collection.is_locked():
name = def_collection.get_label()
if not name:
name = "<unnamed>"
print("The keyring '%s' used for storing passwords is locked, "
"please enter unlock password." % name)
def_collection.unlock()
if def_collection.is_locked():
raise PermissionError("Failed to unlock keyring.")
return SecretStorage(bus, def_collection)
def is_requiring_authentication(self, protocol, server, port,
objname=None):
"""
Retrieve whether the specified server is known to require
authentication.
:param protocol: The protocol that is used to communicate with the
server.
:param server: The server's address.
:param port: The server's port.
:param objname: (Optional) Constrain the search of credentials to the
given shared authentication object.
:return: True if the server requires authentication.
False if it known that it does not.
Return None if the authentication "status" of the server is not
known.
"""
# First, check if the server *is* authenticating.
nattrs = {
'xdg:schema': "org.gnome.keyring.Note",
'application': "whisperity/sync-repositories",
'protocol': protocol,
'server': server,
'port': str(port)
}
if objname:
nattrs['object'] = objname
notes = self._collection.search_items(nattrs)
note = next(notes, None)
if not note:
return None
secret = note.get_secret().decode('utf-8')
if secret == 'False':
return False
elif secret == 'True':
return True
else:
raise ValueError("Non-boolean secret value stored for "
"authentication knowledge.")
def get_credentials(self, protocol, server, port, objname=None):
"""
Retrieve the stored credentials for a specified remote server.
:param protocol: The protocol that is used to communicate with the
server.
:param server: The server's address.
:param port: The server's port.
:param objname: (Optional) Constrain the search of credentials to the
given shared authentication object.
:return: A list of credential pairs (username, password) if credentials
are known. Empty list if there are no credentials stored.
"""
requires_authentication = self.is_requiring_authentication(protocol,
server,
port,
objname)
if requires_authentication is False:
return False
# Now search for the actual credentials.
attrs = {
'xdg:schema': "org.gnome.keyring.NetworkPassword",
'authtype': "username-password",
'application': "whisperity/sync-repositories",
'protocol': protocol,
'server': server,
'port': str(port)
}
if objname:
attrs['object'] = objname
credentials = self._collection.search_items(attrs)
ret = []
for cred in credentials:
ret.append((cred.get_attributes()['user'],
cred.get_secret().decode('utf-8')))
return ret
def set_credential(self, protocol, server, port, user, password,
objname=None, label=None):
"""
Store (or overwrite) a credential for the given remote server.
:param protocol: The protocol that is used to communicate with the
server.
:param server: The server's address.
:param port: The server's port.
:param user: The username to authenticate with.
:param password: The password that is used to authenticate.
:param objname: (Optional) Constrain the credential to the given shared
authentication object.
:param label: (Optional) A label that is attached to the secret item
and shown in the keyring.
"""
attrs = {'xdg:schema': "org.gnome.keyring.NetworkPassword",
'authtype': "username-password",
'application': "whisperity/sync-repositories",
'protocol': protocol,
'server': server,
'port': str(port),
'user': user}
if objname:
attrs['object'] = objname
if not label:
label = "%s password for '%s' on '%s'" % (protocol, user, server)
self._collection.create_item(label, attrs, password, replace=True)
self.set_authenticating(protocol, server, port, objname)
def delete_credential(self, protocol, server, port, user, objname=None):
"""
Delete the credential associated with the specified remote server.
:param protocol: The protocol that is used to communicate with the
server.
:param server: The server's address.
:param port: The server's port.
:param user: The username to authenticate with.
:param objname: (Optional) Constrain the search of credentials to the
given shared authentication object.
"""
attrs = {
'xdg:schema': "org.gnome.keyring.NetworkPassword",
'authtype': "username-password",
'application': "whisperity/sync-repositories",
'protocol': protocol,
'server': server,
'port': str(port),
'user': user
}
if objname:
attrs['object'] = objname
items = self._collection.search_items(attrs)
items = list(items)
if not items:
raise KeyError("No secret found for %s:%s:%s:%s" %
(protocol, server, port, user))
for item in items:
item.delete()
def delete_server(self, protocol, server, port):
"""
Deletes all information (including all credentials) known about the
specified server.
:param protocol: The protocol that is used to communicate with the
server.
:param server: The server's address.
:param port: The server's port.
"""
credentials = self._collection.search_items({
'authtype': "username-password",
'application': "whisperity/sync-repositories",
'protocol': protocol,
'server': server,
'port': str(port)
})
for cred in credentials:
cred.delete()
notes = self._collection.search_items({
'xdg:schema': "org.gnome.keyring.Note",
'application': "whisperity/sync-repositories",
'protocol': protocol,
'server': server,
'port': str(port)
})
for note in notes:
note.delete()
def _store_authentication_bool(self, protocol, server, port, objname,
is_authenticating):
"""
Stores whether the remote server specified needs authentication.
:param protocol: The protocol that is used to communicate with the
server.
:param server: The server's address.
:param port: The server's port.
:param is_authenticating: The value to store in the secure storage.
:param objname: The shared authentication object's identifier to which
the knowledge should be constrained.
"""
if not isinstance(is_authenticating, bool):
raise TypeError("is_authenticating must be boolean.")
attrs = {'xdg:schema': "org.gnome.keyring.Note",
'application': "whisperity/sync-repositories",
'protocol': protocol,
'server': server,
'port': str(port)
}
if objname:
attrs['object'] = objname
label = "Is '%s:%d/%s' for '%s' authenticating?"\
% (server, port, str(objname), protocol)
self._collection.create_item(label, attrs, str(is_authenticating),
replace=True)
def set_authenticating(self, protocol, server, port, objname=None):
"""
Marks the given remote server as a connection that does need
authentication.
:param protocol: The protocol that is used to communicate with the
server.
:param server: The server's address.
:param port: The server's port.
:param objname: (Optional) Constrain the knowledge to the given shared
authentication object.
"""
self._store_authentication_bool(protocol, server, port, objname, True)
def set_unauthenticated(self, protocol, server, port, objname=None):
"""
Marks the given remote server as a connection that does not need
authentication.
This method does NOT automatically remove the associated credentials.
:param protocol: The protocol that is used to communicate with the
server.
:param server: The server's address.
:param port: The server's port.
:param objname: (Optional) Constrain the knowledge to the given shared
authentication object.
"""
self._store_authentication_bool(protocol, server, port, objname, False)
_security_headsup_shown = False
def discuss_keyring_security():
global _security_headsup_shown
if not _security_headsup_shown:
print("--------- SECURITY INFORMATION ----------")
print("Username and password-based authentication details for "
"repositories will be saved into your Keyring or Wallet.")
print("This is a secure solution for storing secret information "
"for your user only!")
print("The keyring and the data within are encrypted, and need to be "
"unlocked every time you start your computer.")
print("(In most cases, this is done automatically at log-in.)")
print("Next time you use this tool, the saved information will be "
"reused, and the details won't be asked for again.")
print("--------- SECURITY INFORMATION ----------")
_security_headsup_shown = True
def ask_user_for_password(keyring, url, parts, can_be_empty=True):
"""
Helper method that nicely asks the user for the authentication credentials
for the given remote server.
:param keyring: The keyring to save the authentication knowledge to.
:param url: The full URL of the remote server. This is only used for
prompting the user.
:param parts: The tuple (protocol, server, port, objname) to save the
credentials for.
:param can_be_empty: Whether an empty username (indicating no
authentication) should be accepted.
"""
print("Entering authentication details for '%s'..." % url)
# Ask for username.
if can_be_empty:
print("Leave username EMPTY if you know the server requires NO "
"authentication.")
username = ''
while not username.strip():
username = input("Username (empty if no authentication): ")
if not username.strip():
if can_be_empty:
# Empty username given.
print("Setting no authentication needed.")
keyring.set_unauthenticated(*parts)
return
else:
print("ERROR: Empty username given.", file=sys.stderr)
# Ask for password.
password = ''
while not password.strip():
password = getpass.getpass("Password for user '%s': " % username)
if not password.strip():
print("ERROR: Empty password given.", file=sys.stderr)
protocol, server, port, objname = parts
keyring.set_credential(protocol, server, port,
username, password,
objname)
return (username, password)
|
{"/sync_repositories/repository/__init__.py": ["/sync_repositories/repository/repository.py", "/sync_repositories/repository/subversion.py", "/sync_repositories/repository/git.py"], "/sync_repositories/repository/subversion.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/credentials/auto_askpass.py": ["/sync_repositories/credentials/__init__.py"], "/sync_repositories/repository/git.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/__main__.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/__init__.py"]}
|
21,648
|
whisperity/sync-repositories
|
refs/heads/master
|
/sync_repositories/credentials/auto_askpass.py
|
"""
SYNOPSIS: Wrapper script that acts as an 'askpass' program, but in fact just
returns the data stored in the keyring.
"""
from copy import deepcopy
import os
import sys
import tempfile
from sync_repositories.credentials import keyring
def create(protocol, host, port, objname):
"""
Sets up an environment through which the program can be re-invoked by
itself. In this new environment, the output will be the username and
password stored in the keyring for the specified server.
Refer to `credentials.keyring` for what the arguments mean.
"""
# Set up an environment in which 'git fetch' will load username and
# password from this script, not prompt the user in terminal.
env = deepcopy(os.environ)
env['GIT_ASKPASS'] = sys.argv[0] # Use the entry point of the script.
env['SR_ASKPASS'] = '1'
env['SR_ASKPASS_PROTOCOL'] = protocol if protocol else ''
env['SR_ASKPASS_SERVER'] = host if host else ''
env['SR_ASKPASS_PORT'] = str(port) if port else '0'
env['SR_ASKPASS_OBJECT'] = objname if objname else ''
handle, filepath = tempfile.mkstemp()
os.write(handle, 'U'.encode('ascii'))
os.close(handle)
env['SR_ASKPASS_TEMP'] = filepath
return env
def create_with_credentials(username, password, protocol, host, port, objname):
"""
Sets up an environment through which the program can be re-invoked by
itself, but instead of the data stored actually in the keyring, returns a
pre-set username and password.
The credentials don't *actually* leave the keyring, as a temporary store
is used by the wrapper.
"""
storage = keyring.SecretStorage.get_storage()
protocol = 'temp'
objname = objname + '__TEMP'
storage.set_credential(protocol, host, port, username, password, objname,
label="Temporary password for Sync-Repos ASKPASS")
env = create(protocol, host, port, objname)
env['SR_ASKPASS_TEMPORARY_CREDENTIAL'] = '1'
return env
def execute():
if 'SR_ASKPASS_PROTOCOL' not in os.environ or \
'SR_ASKPASS_SERVER' not in os.environ or \
'SR_ASKPASS_PORT' not in os.environ or \
'SR_ASKPASS_OBJECT' not in os.environ or \
'SR_ASKPASS_TEMP' not in os.environ:
print("ERROR! Bad invocation -- environment wasn't set up.",
file=sys.stderr)
sys.exit(1)
# We can safely assume that the storage obtained here is unlocked, as this
# script should be called from under __main__ anyways.
storage = keyring.SecretStorage.get_storage()
objname = os.environ['SR_ASKPASS_OBJECT']
if not objname: # Might be empty string.
objname = None
credentials = storage.get_credentials(os.environ['SR_ASKPASS_PROTOCOL'],
os.environ['SR_ASKPASS_SERVER'],
os.environ['SR_ASKPASS_PORT'],
objname)
if not credentials:
# If no credentials are found, bail out. This *usually* shouldn't
# happen, as the main script preemptively asks the user for
# credentials.
print("invalid")
sys.exit(0) # Need to exit with "success" here so the caller believes.
username, password = credentials[0]
# Check what the invoker is searching for. The first invocation for a
# repository queries a username, and the second queries the password.
clean_up_temp_file = False
with open(os.environ['SR_ASKPASS_TEMP'], 'r+') as f:
content = f.readline().rstrip()
if content == 'U':
print(username, end='') # Actual output to invoker.
f.truncate(0)
f.seek(0)
f.write('P')
elif content == 'P':
print(password, end='') # Actual output to invoker.
f.truncate(0)
clean_up_temp_file = True
if clean_up_temp_file:
os.unlink(os.environ['SR_ASKPASS_TEMP'])
if os.environ.get('SR_ASKPASS_TEMPORARY_CREDENTIAL', None) and \
os.environ['SR_ASKPASS_PROTOCOL'] == 'temp' and \
objname is not None and \
objname.endswith('__TEMP'):
# Delete a temporary credential if the wrapper invocation was
# created with create_with_credentials.
storage.delete_server(os.environ['SR_ASKPASS_PROTOCOL'],
os.environ['SR_ASKPASS_SERVER'],
os.environ['SR_ASKPASS_PORT'])
sys.exit(0)
|
{"/sync_repositories/repository/__init__.py": ["/sync_repositories/repository/repository.py", "/sync_repositories/repository/subversion.py", "/sync_repositories/repository/git.py"], "/sync_repositories/repository/subversion.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/credentials/auto_askpass.py": ["/sync_repositories/credentials/__init__.py"], "/sync_repositories/repository/git.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/__main__.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/__init__.py"]}
|
21,649
|
whisperity/sync-repositories
|
refs/heads/master
|
/sync_repositories/repository/repository.py
|
import urllib.parse
class Repository:
def __init__(self, path, datadir, kind):
self.path = path
self.datadir = datadir
self.kind = kind
self.urls = []
def get_authentication_method(self, remote):
"""
Retrieve the authentication method 'backend' needed to authenticate
against a given remote.
"""
raise NotImplementedError()
def get_remote_parts(self, remote):
"""
Returns a tuple of (`protocol`, `server hostname`, `port` and
`object`).
If `port` is not known, it is replaced by `0`.
:returns: A pair of (url, parts) where `url` is the full URL, and
`parts` is a tuple containing `protocol`, `hostname`, `port` and
optionally the server sub-object (such as folder) in this order.
"""
url = next(filter(lambda r: r[0] == remote, self.urls))[1]
parse_result = urllib.parse.urlparse(url, 'unk')
protocol = self.kind + '-' + parse_result.scheme
host = parse_result.hostname
port = parse_result.port if parse_result.port else 0
return (url, (protocol, host, port, self.get_remote_objname(remote)))
def get_remotes(self):
"""
Returns a generator that produces, for each remote repository URL known
for the instance, a triple of (`protocol`, `server hostname`
and `port`).
If `port` is not known, it is replaced by `0`.
:returns: A triple of (remote, url, parts) where `remote` is the
name of the remote, `url` is the full URL, and `parts` is a
tuple containing `protocol`, `hostname`, `port` and optionally the
server sub-object (such as folder) in this order.
"""
for remote, url in self.urls:
parse_result = urllib.parse.urlparse(url, 'unk')
protocol = self.kind + '-' + parse_result.scheme
host = parse_result.hostname
port = parse_result.port if parse_result.port else 0
yield (remote, url,
(protocol, host, port, self.get_remote_objname(remote)))
def get_updater_for(self, remote):
"""
Return a factory function for the current repository that can be used
to instantiate an `Updater` instance.
"""
raise NotImplementedError()
def get_auth_requirement_detector_for(self, remote):
"""
Returns a factory function for the current repository that can be used
to instantiate an `AuthenticationRequirementChecker` instance.
"""
raise NotImplementedError()
def get_remote_objname(self, remote):
"""
Get an identifying "object name" for the current repository and
specified remote. This is used to distinguish remotes on the same
server endpoint.
"""
raise NotImplementedError()
def __repr__(self):
return '(' + type(self).__name__ + " @ " + self.path + ')'
class AuthenticationRequirementChecker():
def __init__(self, repository):
self._repository = repository
def check(self):
"""
Performs checking for whether the backend needs authentication.
:return: Whether authentication is needed.
"""
raise NotImplementedError()
def check_credentials(self):
"""
If the checker supports checking validy of credentials, performs this
step.
:return: Whether the credentials pass.
"""
raise NotImplementedError()
class Updater:
def __init__(self, repository):
self._repository = repository
def update(self):
"""
Performs the update action for the repository.
:return: False if the update failed, True if successful.
"""
raise NotImplementedError()
|
{"/sync_repositories/repository/__init__.py": ["/sync_repositories/repository/repository.py", "/sync_repositories/repository/subversion.py", "/sync_repositories/repository/git.py"], "/sync_repositories/repository/subversion.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/credentials/auto_askpass.py": ["/sync_repositories/credentials/__init__.py"], "/sync_repositories/repository/git.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/__main__.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/__init__.py"]}
|
21,650
|
whisperity/sync-repositories
|
refs/heads/master
|
/setup.py
|
from distutils.core import setup
import setuptools
setup(
name='sync-repositories',
packages=[
'sync_repositories',
'sync_repositories.credentials',
'sync_repositories.repository'
],
entry_points={
'console_scripts': [
'sync-repos = sync_repositories.__main__:_main'
]
},
version='0.1',
license='MIT',
description="""Helper script to automatically "update" (in some sense of
the word) every source code repository you have""",
author='Whisperity',
author_email='whisperity@no.no',
url='http://github.com/whisperity/sync-repositories',
download_url='http://github.com/whisperity/sync-repositories/' +
'archive/v_01.tar.gz',
keywords=['git', 'svn', 'repository', 'source control', 'version control'],
install_requires=[
'GitPython',
'secretstorage',
'svn'
],
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License'
'Operating System :: POSIX :: Linux',
'Operating System :: Unix',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
]
)
|
{"/sync_repositories/repository/__init__.py": ["/sync_repositories/repository/repository.py", "/sync_repositories/repository/subversion.py", "/sync_repositories/repository/git.py"], "/sync_repositories/repository/subversion.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/credentials/auto_askpass.py": ["/sync_repositories/credentials/__init__.py"], "/sync_repositories/repository/git.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/__main__.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/__init__.py"]}
|
21,651
|
whisperity/sync-repositories
|
refs/heads/master
|
/sync_repositories/repository/git.py
|
import os
import subprocess
import sys
import urllib.parse
try:
import git
except ImportError:
print("Error! `GitPython` is a dependency, please install.",
file=sys.stderr)
raise
from sync_repositories.credentials import auto_askpass
from sync_repositories.credentials import Backends
from .repository import AuthenticationRequirementChecker, Repository, Updater
class Git(Repository):
class UsernamePasswordAuthenticationChecker(
AuthenticationRequirementChecker):
"""
Checking engine for Git repositories that might use username-password
based HTTP(S) authentication.
"""
def __init__(self, repository, remote, parts,
username=None, password=None):
super().__init__(repository)
self._remote = remote
self._parts = parts
if username is None and password is None:
self._credentials = False
elif username is not None and password is not None:
self._credentials = True
else:
raise ValueError("Authentication check for Git HTTP "
"repositories with either both username and "
"password, or none of it.")
self._username = username
self._password = password
def _fun(self):
command = ['git', 'remote', 'show', self._remote]
# Create an 'askpass' wrapper that will always return invalid, but
# if asked to return something, will signal us through a control
# file.
if not self._credentials:
env = auto_askpass.create(*self._parts)
else:
env = auto_askpass.create_with_credentials(self._username,
self._password,
*self._parts)
try:
subprocess.run(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding='utf-8',
cwd=self._repository.path,
check=True,
env=env)
# If the call above succeeds, the repository did not need
# authentication.
return False
except subprocess.CalledProcessError as cpe:
if "Authentication failed" in cpe.output:
return True
raise
def check(self):
return self._fun()
def check_credentials(self):
return not self._fun()
class UsernamePasswordWrappingUpdater(Updater):
"""
Updates a Git repository clone with optionally providing
username and password authentication to the updater executable.
"""
def __init__(self, repository, remote, parts):
super().__init__(repository)
self._remote = remote
self._parts = parts
def update(self):
update = 'update' if self._repository.custom_update_command \
else 'fetch'
command = ['git', update, self._remote]
# Wrap the authentication details into a dummy script, as Git
# updating with username and password asks from an inner process,
# and we can't feed STDIN into it.
env = auto_askpass.create(*self._parts)
# Create the updater process.
path = self._repository.path
try:
print("Updating '%s'..." % path)
proc = subprocess.run(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding='utf-8',
cwd=path,
check=True,
env=env)
print(proc.stdout)
return True
except subprocess.CalledProcessError as cpe:
print("Update failed for '%s':" % path, file=sys.stderr)
print(cpe.output, file=sys.stderr)
print(str(cpe), file=sys.stderr)
return False
def __init__(self, path, datadir):
super().__init__(path, datadir, 'git')
# Check the repository's configuration on how it shall be updated.
repo = git.Repo(datadir)
self.urls = []
self._auth_methods = {} # Parse authentication methods for remotes.
for remote in repo.remotes:
for url in remote.urls:
parsed = urllib.parse.urlparse(url)
if parsed.scheme in ['http', 'https', 'ftp', 'ftps']:
# HTTP and FTP protocol may authenticate with
# username-password.
self._auth_methods[remote.name] = Backends.KEYRING
elif parsed.scheme in ['git', 'file']:
# The old-style Git and local-clone file protocol does not
# authenticate.
self._auth_methods[remote.name] = None
else:
if not parsed.netloc and parsed.scheme:
# If "netloc" wasn't parsed, the repository URL is
# using the 'example.org:foobar.git' shorthand syntax
# for 'ssh://example.org/foobar.git'.
url = 'ssh://' + parsed.scheme + '/' + parsed.path
self._auth_methods[remote.name] = Backends.SSH_AGENT
self.urls.append((remote.name, url))
self.urls = sorted(self.urls)
# Try to see if the user has a custom 'update' command alias in their
# Git config.
# (To ensure this works as it would in a Shell, we need to load every
# configuration script, not just the repository's own.)
config_command = ['git', 'config', '--get', 'alias.update']
try:
subprocess.check_output(config_command, cwd=self.path)
self.custom_update_command = True
except subprocess.CalledProcessError:
self.custom_update_command = False
def get_authentication_method(self, remote):
return self._auth_methods[remote]
def get_remote_objname(self, remote):
# Return the path on the Git server to the repository.
url = next(filter(lambda r: r[0] == remote, self.urls))[1]
parsed = urllib.parse.urlparse(url)
return parsed.path if parsed.path else ""
def get_auth_requirement_detector_for(self, remote):
method = self._auth_methods[remote]
if method is None:
class _cls():
"""
An authentication validator that always validates everything
for the case when no authentication is to be done.
"""
def check(self):
return False
def check_credentials(self):
return True
def _factory():
return _cls()
elif method == Backends.KEYRING:
def _factory(username=None, password=None):
return Git.UsernamePasswordAuthenticationChecker(
self, remote, self.get_remote_parts(remote)[1],
username, password)
else:
class _cls():
"""
An authentication validator that always validates everything
for the case when no authentication is to be done.
"""
def check(self):
return False
def check_credentials(self):
return True
def _factory():
return _cls()
# raise NotImplementedError("Not implemented for %s" % remote)
return _factory
def get_updater_for(self, remote):
method = self._auth_methods[remote]
if method is None or method == Backends.KEYRING:
def _factory(username, password):
# This function conveniently ignores the username and password
# argument, as Git username updating uses a wrapper script.
return Git.UsernamePasswordWrappingUpdater(
self, remote, self.get_remote_parts(remote)[1])
else:
raise NotImplementedError("Not implemented for %s" % remote)
return _factory
|
{"/sync_repositories/repository/__init__.py": ["/sync_repositories/repository/repository.py", "/sync_repositories/repository/subversion.py", "/sync_repositories/repository/git.py"], "/sync_repositories/repository/subversion.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/credentials/auto_askpass.py": ["/sync_repositories/credentials/__init__.py"], "/sync_repositories/repository/git.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/__main__.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/__init__.py"]}
|
21,652
|
whisperity/sync-repositories
|
refs/heads/master
|
/sync_repositories/credentials/ssh_agent.py
|
import sys
try:
import sshconf
except ImportError:
print("Error! `sshconf` is a dependency, please install.",
file=sys.stderr)
sys.exit(-1)
|
{"/sync_repositories/repository/__init__.py": ["/sync_repositories/repository/repository.py", "/sync_repositories/repository/subversion.py", "/sync_repositories/repository/git.py"], "/sync_repositories/repository/subversion.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/credentials/auto_askpass.py": ["/sync_repositories/credentials/__init__.py"], "/sync_repositories/repository/git.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/__main__.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/__init__.py"]}
|
21,653
|
whisperity/sync-repositories
|
refs/heads/master
|
/sync_repositories/__main__.py
|
#!/usr/bin/env python3
"""
SYNOPSIS: Automatically updates every found source code repository in the
current tree, or the specified path.
"""
import argparse
import os
import subprocess
import sys
from sync_repositories.credentials import Backends
from sync_repositories.credentials import keyring as kr
from sync_repositories.repository import get_repositories
def _main():
# Go into askpass-wrapper mode if the environment specifies it.
if 'SR_ASKPASS' in os.environ:
from sync_repositories.credentials import auto_askpass
auto_askpass.execute()
# Make sure execution doesn't flow through.
raise RuntimeError("askpass_wrapper didn't terminate properly.")
ARGS = argparse.ArgumentParser(
description="""Synchronise source control repositories found in the
current tree.""",
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
ARGS.add_argument('root_folder',
help="""The root of the directory tree where update
should be run.""",
nargs='?',
default=os.getcwd())
ARGS.add_argument('--do-not-ask', '--daemon', '-d',
dest='daemon',
action='store_true',
help="""Perform an automatic update of repositories,
skipping a repository if user interaction
would be necessary.""")
argv = ARGS.parse_args()
keyring = kr.SecretStorage.get_storage()
print("Checking '%s' for repositories..." % argv.root_folder,
file=sys.stderr)
repository_to_update_data = {}
# Perform a check that every repository's authentication status is known.
for repo in get_repositories(argv.root_folder):
repo_data = list()
for remote, url, parts in repo.get_remotes():
check_authentication = keyring.is_requiring_authentication(*parts)
needs_credentials, can_update = None, False
if check_authentication is None:
# We don't know yet whether the server requires
# authentication or not.
auth_checker = repo.get_auth_requirement_detector_for(
remote)()
try:
if auth_checker.check():
keyring.set_authenticating(*parts)
needs_credentials = True
else:
keyring.set_unauthenticated(*parts)
needs_credentials = False
can_update = True
except subprocess.CalledProcessError as cpe:
print("Failed to execute authentication check for "
"repository '%s' remote '%s':"
% (repo.path, remote))
print(cpe)
continue
elif check_authentication is False:
# We know that the server does not require authentication.
needs_credentials, can_update = False, True
else:
# We know that the server requires authentication.
needs_credentials = True
auth_backend = repo.get_authentication_method(remote)
if auth_backend == Backends.KEYRING:
if needs_credentials:
# If we realised that credentials are needed, check if
# credentials are properly known.
credentials_stored = keyring.get_credentials(*parts)
if not credentials_stored:
print("The repository '%s' has a remote server '%s' "
"is connected to, but the authentication "
"details for this server are not known!"
% (repo.path, remote))
if not argv.daemon:
# ... unless running in daemon mode, in which
# case the user won't be asked.
kr.discuss_keyring_security()
u, p = kr.ask_user_for_password(
keyring, url, parts, can_be_empty=False)
# Check if the given credentials are valid.
auth_checker = repo \
.get_auth_requirement_detector_for(remote)(
u, p)
if auth_checker.check_credentials():
can_update = True
else:
print("Invalid credentials given!",
file=sys.stderr)
protocol, server, port, objname = parts
keyring.delete_credential(protocol,
server,
port,
u,
objname)
else:
can_update = True
if can_update:
repo_data.append((remote, url, parts))
else:
print("... Skipping this repository from update.")
continue
repository_to_update_data[repo] = repo_data
# Update repositories that had been selected for actual update.
print("Performing repository updates...")
for repo, data in repository_to_update_data.items():
for remote, url, parts in data:
print("Updating '%s' from remote '%s'..." % (repo.path, remote))
auth_backend = repo.get_authentication_method(remote)
update_success = False
if auth_backend == Backends.KEYRING:
kr_creds = keyring.get_credentials(*parts)
if not kr_creds:
# If the server doesn't require authentication, don't
# provide credentials.
kr_creds = [(None, None)]
for kr_cred in kr_creds:
updater = repo.get_updater_for(remote)(*kr_cred)
update_success = update_success or updater.update()
if not update_success:
print("Failed to update '%s' from remote '%s'!"
% (repo.path, remote),
file=sys.stderr)
if __name__ == '__main__':
_main()
|
{"/sync_repositories/repository/__init__.py": ["/sync_repositories/repository/repository.py", "/sync_repositories/repository/subversion.py", "/sync_repositories/repository/git.py"], "/sync_repositories/repository/subversion.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/credentials/auto_askpass.py": ["/sync_repositories/credentials/__init__.py"], "/sync_repositories/repository/git.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/repository.py"], "/sync_repositories/__main__.py": ["/sync_repositories/credentials/__init__.py", "/sync_repositories/repository/__init__.py"]}
|
21,667
|
fridafu/mean
|
refs/heads/master
|
/RBmain.py
|
from test_mean import test_ints, test_double, test_long
num_list = [1,2,3,4,5]
test_ints(num_list)
test_double(num_list)
test_long()
|
{"/RBmain.py": ["/test_mean.py"], "/test_mean.py": ["/RB1.py"]}
|
21,668
|
fridafu/mean
|
refs/heads/master
|
/RB1.py
|
msg = "\nU cannot do it with the zero under there!!!"
def mean(num_list):
if len(num_list)== 0:
raise Exception(msg)
else:
return sum(num_list)/len(num_list)
def mean2(num_list):
try:
return sum(num_list)/len(num_list)
except ZeroDivisionError as detail:
raise ZeroDivisionError(detail.__str__() + msg)
except TypeError as detail:
msg2 = "\n use numbers "
raise TypeError(detail.__str__() + msg2)
|
{"/RBmain.py": ["/test_mean.py"], "/test_mean.py": ["/RB1.py"]}
|
21,669
|
fridafu/mean
|
refs/heads/master
|
/test_mean.py
|
from RB1 import *
numlist = [1,2,3,4,5]
def test_ints(nlist=numlist):
obs = mean(nlist)
exp = 3
assert obs == exp
def test_double(nlist=numlist):
obs = mean(nlist)
#nlist = [1,2,3,4]
exp = 3
assert obs == exp
def test_long():
big = 100000000
obs = mean(range(1,big))
exp = big/2.0
assert obs == exp
def test_zero():
num_list = [0,2,4,6]
obs = mean(num_list)
exp = 3
assert obs == exp
"""
def test_complex():
#testing for complex numbers
#as arithmetic mean of complex numbers is meaningless
num_list = [2+3j,3+4j,-32-2j]
obs = mean(num_list)
exp = NotImplemented
assert obs==exp
"""
#test_ints()
#test_double()
#test_long()
|
{"/RBmain.py": ["/test_mean.py"], "/test_mean.py": ["/RB1.py"]}
|
21,773
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/polls/urls.py
|
from polls import views
from django.conf.urls import url
urlpatterns = [
url(r'^login/$', views.authenticate_view, name="login"),
url(r'^logout/$', views.logout_view, name="logout"),
url(r'^check/$', views.check_authentication_view, name="check"),
url(r'^candidates/$', views.CandidateView.as_view()),
url(r'^candidates/(?P<pk>[0-9]+)/$', views.CandidateDetailView.as_view(), name="candidate"),
url(r'^elections/$', views.ElectionView.as_view()),
url(r'^elections/(?P<pk>[0-9]+)/$', views.ElectionDetailView.as_view(), name="election"),
url(r'^statistics/$', views.StatisticsView.as_view(), name="statistics"),
url(r'^trends/$', views.TrendView.as_view()),
url(r'^trends/(?P<pk>[0-9]+)/$', views.TrendDetailView.as_view(), name="trends"),
]
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,774
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/import_data/urls.py
|
from django.conf.urls import url
from import_data import views
urlpatterns = [
url(r'^french-candidates/$', views.french_candidates, name='import_french_candidates'),
url(r'^from-wikipedia/$', views.from_wikipedia, name='import_from_wikipedia'),
url(r'^get-tweets/$', views.get_trends, name='get_tweets'),
url(r'^get_twitter_trends/(?P<election_id>[0-9]+)/(?P<start_date>\w+)/(?P<end_date>\w+)/(?P<tag>\w+)/$', views.get_twitter_trends, name='get_tweets'),
url(r'^french-elections/$', views.french_elections, name='import_french_elections'),
url(r'^google_analysis/(?P<election_id>[0-9]+)/$', views.analysis_from_google, name = 'google_analysis'),
url(r'^from-sondage-en-france/$', views.sondage_2012, name = 'sondage2012'),
url(r'^from-wikipedia-2007/$', views.sondage_2007, name = 'sondage2007'),
url(r'^from-france-politique-2002/$', views.sondage_2002, name = 'sondage2002'),
]
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,775
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/polls/migrations/0002_auto_20161212_1217.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-12 11:17
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('polls', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Candidate',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('surname', models.CharField(max_length=50)),
('birthDate', models.DateTimeField(verbose_name='date published')),
('birthPlace', models.DateTimeField(verbose_name='date published')),
],
),
migrations.CreateModel(
name='DetailedResults',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('voteNumber', models.IntegerField(default=0)),
('candidate', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Candidate')),
],
),
migrations.CreateModel(
name='Election',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateTimeField(verbose_name='date published')),
('place', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Place')),
],
),
migrations.CreateModel(
name='Party',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('year_in_school', models.CharField(choices=[('FL', 'FarLeft'), ('LE', 'Left'), ('CE', 'Center'), ('RI', 'Right'), ('FR', 'FarRight')], default='CE', max_length=2)),
('creationDate', models.DateTimeField(verbose_name='date published')),
('place', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Place')),
],
),
migrations.CreateModel(
name='Poll',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateTimeField(verbose_name='date published')),
('score', models.DecimalField(decimal_places=2, max_digits=4)),
('weight', models.DecimalField(decimal_places=2, max_digits=4)),
('candidate', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Candidate')),
('election', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Election')),
('place', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Place')),
],
),
migrations.CreateModel(
name='PollInstitute',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('grade', models.DecimalField(decimal_places=2, max_digits=4)),
],
),
migrations.CreateModel(
name='Position',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('position', models.CharField(max_length=50)),
],
),
migrations.CreateModel(
name='Result',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('votingResult', models.DecimalField(decimal_places=2, max_digits=4)),
('candidate', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Candidate')),
('election', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Election')),
],
),
migrations.CreateModel(
name='Role',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('beginningDate', models.DateTimeField(verbose_name='date published')),
('endDate', models.DateTimeField(blank=True, null=True, verbose_name='date published')),
('election', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='polls.Election')),
('positionType', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='polls.Position')),
],
),
migrations.AddField(
model_name='poll',
name='pollInstitute',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.PollInstitute'),
),
migrations.AddField(
model_name='detailedresults',
name='election',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Election'),
),
migrations.AddField(
model_name='detailedresults',
name='place',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Place'),
),
]
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,776
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/import_data/tests.py
|
from django.test import TestCase
from views import save_to_database, get_tweets_by_day
def test_aggregate_by_day(filtered_list, day):
# save_to_database('2017-01-15', 'PrimaireGauche', 0)
save_to_database('2017-01-15','PrimaireGauche',0,election)
print("Kasra fragile")
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,777
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/polls/migrations/0009_auto_20170117_1139.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-01-17 10:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0008_auto_20170116_1013'),
]
operations = [
migrations.AlterField(
model_name='result',
name='voting_result',
field=models.DecimalField(blank=True, decimal_places=2, max_digits=4, null=True),
),
]
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,778
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/polls/views.py
|
from polls.models import Candidate, Election, Trend, Statistics
from libs.time import french_format_to_datetime
from django import forms
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.core import serializers
from django.http import HttpResponse, HttpResponseForbidden, HttpResponseRedirect
from django.shortcuts import render
from django.views import View
from django.views.generic import ListView, DetailView
from django.views.generic.edit import FormView
import json
def authenticate_view(request):
return render(request, 'polls/login.html')
def check_authentication_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return HttpResponseRedirect('/polls/statistics/')
return HttpResponseForbidden('The authentication failed. The username or password is wrong.')
def logout_view(request):
logout(request)
return HttpResponseRedirect('/polls/login/')
class CandidateView(ListView):
model = Candidate
template_name = "polls/candidate_list.html"
def get_queryset(self, *args, **kwargs):
queryset = Candidate.objects.all()
queryset.filter(**kwargs)
return queryset
class CandidateDetailView(DetailView):
model = Candidate
template_name = "polls/candidate_detail.html"
class ElectionView(ListView):
model = Election
template_name = "polls/election_list.html"
def get_queryset(self, *args, **kwargs):
queryset = Election.objects.all()
queryset.filter(**kwargs)
return queryset
class ElectionDetailView(DetailView):
model = Election
template_name = "polls/election_detail.html"
class TrendView(ListView):
model = Trend
template_name = "polls/trend_list.html"
def get_queryset(self, *args, **kwargs):
queryset = Trend.objects.all()
queryset.filter(**kwargs)
return queryset
class TrendDetailView(DetailView):
model = Trend
template_name = "polls/trend_detail.html"
class StatisticsView(ListView):
context_object_name = "statistics_list"
model = Statistics
template_name = "polls/statistics_form.html"
def get_context_data(self, *args, **kwargs):
context = super(StatisticsView, self).get_context_data(**kwargs)
elections = Election.objects.all()
context['elections'] = elections
context['json_elections'] = [int(election.id) for election in elections]
candidates = Candidate.objects.all()
candidates = {int(candidate.id) : "'%s %s'" % (candidate.name, candidate.surname) for candidate in candidates}
context["candidates"] = json.dumps(candidates)
candidates_by_election = {int(election.id) : [int(candidate.id) for candidate in election.candidates.all()] for election in elections}
context["candidates_by_election"] = candidates_by_election
context["statistics"] = Statistics.objects.reverse()
return context
def post(self, request, *args, **kwargs):
user = request.user
election_id = request.POST.get("electionId", "")
candidate_id = request.POST.get("candidateId", "")
start_date = request.POST.get("startDate", "")
end_date = request.POST.get("endDate", "")
try:
election = Election.objects.get(id=election_id)
candidate = Candidate.objects.get(id=candidate_id)
start_date = french_format_to_datetime(start_date)
end_date = french_format_to_datetime(end_date)
except Election.DoesNotExist:
return HttpResponseNotFound("Election not found")
except Candidate.DoesNotExist:
return HttpResponseNotFound("Candidate not found")
statistic = Statistics(user=user, election=election, candidate=candidate, score=0, start_date=start_date, end_date=end_date)
results = statistic.get_results()
statistic.score = self.get_score(results)
statistic.save()
previous_statistics = Statistics.objects.reverse()
return render(request, 'polls/statistics.html', {'previous_statistics':previous_statistics, 'statistic': statistic, 'results':results[1:]})
def get_score(self, results):
twitter_weight_sum = float(results[0]["weight_sum"] or 1)
twitter_candidate_weight_sum = float(results[1]["weight_sum"] or 1)
twitter_average = results[1]["average"] or 0
google_average = results[2]["average"] or 0
return (1 + 0.2*twitter_average)*(google_average + twitter_candidate_weight_sum/twitter_weight_sum)/2
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,779
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/twitter/test.py
|
from functions import produce_json, different_classes
different_classes()
produce_json('2017-01-15', 'PrimaireGauche')
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,780
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/polls/models.py
|
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.core.validators import URLValidator
from django.db import models
from django.db.models import Avg, Count, Min, Max, StdDev, Sum
from django.template.defaultfilters import truncatechars
from libs.time import datetime_to_string
# Create your models here.
class Place(models.Model):
country = models.TextField(max_length=50)
region = models.TextField(max_length=50, blank=True, null=True)
department = models.TextField(max_length=50, blank=True, null=True)
county = models.TextField(max_length=50, blank=True, null=True)
city = models.TextField(max_length=50, blank=True, null=True)
def __str__(self):
output = []
for attr, value in self.__dict__.iteritems():
if attr not in ["id", "_state"] and value:
output.append(value)
return str(output)
def __unicode__(self):
output = []
for attr, value in self.__dict__.iteritems():
if attr not in ["id", "_state"] and value:
output.append(value)
return ", ".join(output)
class Party(models.Model):
name = models.CharField(max_length=50)
FARLEFT = 'FL'
LEFT = 'LE'
CENTER = 'CE'
RIGHT = 'RI'
FARRIGHT = 'FR'
ORIENTATION_CHOICES = (
(FARLEFT, 'FarLeft'),
(LEFT, 'Left'),
(CENTER, 'Center'),
(RIGHT, 'Right'),
(FARRIGHT, 'FarRight'),
)
political_orientation = models.CharField(
max_length=2,
choices=ORIENTATION_CHOICES,
default=CENTER,
)
creation_date = models.DateTimeField(blank=True, null=True)
parent = models.ForeignKey('Party', on_delete=models.CASCADE, blank = True, null = True)
place = models.ForeignKey(Place, on_delete=models.CASCADE)
pass
class Candidate(models.Model):
name = models.CharField(max_length=50)
surname = models.CharField(max_length=50)
birth_date = models.DateTimeField(blank=True, null=True)
birth_place = models.ForeignKey(Place, related_name="custom_birth_place", on_delete=models.CASCADE, blank=True, null=True)
nationality = models.ForeignKey(Place, related_name="custom_nationality", on_delete=models.CASCADE, blank=True, null=True)
image_url = models.TextField(validators=[URLValidator()], blank=True, null=True)
party = models.ForeignKey(Party, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return self.name + " " + self.surname
def __unicode__(self):
return self.name + " " + self.surname
@property
def image(self):
return self.image_url
@property
def complete_name(self):
return "%s %s" % (self.name, self.surname)
class Election(models.Model):
name = models.CharField(max_length=50,blank=True, null=True)
date = models.DateTimeField(blank=True, null=True)
place = models.ForeignKey(Place, on_delete=models.CASCADE)
candidates = models.ManyToManyField(
Candidate,
through='Result',
through_fields=('election', 'candidate'),
)
@property
def print_name(self):
if self.name == None:
return ("Election du %s" % self.date)
return "%s %s" % (self.name, self.date)
class Result(models.Model):
candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE)
election = models.ForeignKey(Election, on_delete=models.CASCADE)
voting_result = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True)
class TrendSource(models.Model):
name = models.CharField(max_length=50)
grade = models.DecimalField(blank=True, null=True, max_digits=4,decimal_places=2)
def __str__(self):
return self.name + " - " + ("grade : %s" % (self.grade))
def __unicode__(self):
return self.name + " - " + ("grade : %s" % (self.grade))
class Trend(models.Model):
place = models.ForeignKey(Place, on_delete=models.CASCADE)
date = models.DateTimeField(blank=True, null=True)
election = models.ForeignKey(Election, on_delete=models.CASCADE)
candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE)
score = models.DecimalField(max_digits=10,decimal_places=3)
weight = models.DecimalField(blank=True, null=True, max_digits=10,decimal_places=3)
trend_source = models.ForeignKey(TrendSource, on_delete=models.CASCADE)
def __unicode__(self):
output = []
for attr, value in self.__dict__.iteritems():
if attr in ["date"]:
output.append(datetime_to_string(value))
elif attr in ["place", "election", "candidate", "score", "weight", "trend_source"]:
output.append(str(value))
elif attr not in ["id", "_state"] and value:
output.append(str(value))
return ", ".join(output)
class PoliticalFunction(models.Model):
position = models.CharField(max_length=200)
@property
def short_description(self):
return truncatechars(self.position, 100)
def __str__(self):
return self.position
def __unicode__(self):
return self.position
class Role(models.Model):
candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE, blank=True, null=True)
beginning_date = models.DateTimeField(blank=True, null=True)
end_date = models.DateTimeField(blank=True, null=True)
election = models.ForeignKey(Election, on_delete=models.CASCADE, blank=True, null=True)
position_type = models.ForeignKey(PoliticalFunction, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return str(self.position_type_id) + " " + str(self.candidate_id)
def __unicode__(self):
output = []
for attr, value in self.__dict__.iteritems():
if attr in ["beginning_date", "end_date"] and value:
output.append(datetime_to_string(value))
elif attr in ["candidate", "election", "position_type"]:
output.append(str(value))
elif attr not in ["id", "_state"] and value:
output.append(value)
return ", ".join(map(str, output))
class DetailedResults(models.Model):
place = models.ForeignKey(Place, on_delete=models.CASCADE)
election = models.ForeignKey(Election, on_delete=models.CASCADE)
candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE)
vote_number = models.IntegerField(default=0)
class Statistics(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
election = models.ForeignKey(Election, on_delete=models.CASCADE)
candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE)
score = models.DecimalField(max_digits=4 ,decimal_places=3)
start_date = models.DateTimeField(blank=True, null=True)
end_date = models.DateTimeField(blank=True, null=True)
def get_results(self):
twitter = TrendSource.objects.get(name="Twitter")
twitter_weight_sum = Trend.objects.filter(
trend_source_id=twitter.id,
date__gte=self.start_date,
date__lte=self.end_date).aggregate(weight_sum=Sum("weight"))
twitter_stats = Trend.objects.filter(
trend_source_id=twitter.id,
candidate_id=self.candidate.id,
date__gte=self.start_date,
date__lte=self.end_date).aggregate(average=Avg("score"), weight_sum=Sum("weight"), standard_deviation=StdDev("score"), min_value=Min("score"), max_value=StdDev("score"))
google = TrendSource.objects.get(name="Google Trends")
google_stats = Trend.objects.filter(
trend_source_id=google.id,
candidate_id=self.candidate.id,
election_id=self.election.id,
date__gte=self.start_date,
date__lte=self.end_date).aggregate(average=Avg("score"), standard_deviation=StdDev("score"), min_value=Min("score"), max_value=StdDev("score"))
return [twitter_weight_sum, twitter_stats, google_stats]
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,781
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/polls/migrations/0007_auto_20170109_1229.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-01-09 11:29
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('polls', '0006_auto_20161214_2016'),
]
operations = [
migrations.CreateModel(
name='Trend',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateTimeField(blank=True, null=True)),
('score', models.DecimalField(decimal_places=2, max_digits=4)),
('weight', models.DecimalField(blank=True, decimal_places=2, max_digits=4, null=True)),
],
),
migrations.CreateModel(
name='TrendSource',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('grade', models.DecimalField(blank=True, decimal_places=2, max_digits=4, null=True)),
],
),
migrations.RemoveField(
model_name='poll',
name='candidate',
),
migrations.RemoveField(
model_name='poll',
name='election',
),
migrations.RemoveField(
model_name='poll',
name='place',
),
migrations.RemoveField(
model_name='poll',
name='poll_institute',
),
migrations.AddField(
model_name='candidate',
name='nationality',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='custom_nationality', to='polls.Place'),
),
migrations.AddField(
model_name='role',
name='candidate',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='polls.Candidate'),
),
migrations.AlterField(
model_name='candidate',
name='birth_place',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='custom_birth_place', to='polls.Place'),
),
migrations.DeleteModel(
name='Poll',
),
migrations.DeleteModel(
name='PollInstitute',
),
migrations.AddField(
model_name='trend',
name='candidate',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Candidate'),
),
migrations.AddField(
model_name='trend',
name='election',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Election'),
),
migrations.AddField(
model_name='trend',
name='place',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Place'),
),
migrations.AddField(
model_name='trend',
name='trend_source',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.TrendSource'),
),
]
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,782
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/polls/tests.py
|
from models import PoliticalFunction
from django.test import TestCase
class PoliticalFunctionTests(TestCase):
def test_short_description(self):
"""
Should return a short description of the field position
"""
position = "European Commissioner for European Commissioner for Economic" \
+ " and Monetary Affairs and the Euro|Economic and Financial Affairs, " \
+ "European Commissioner for Taxation and Customs Union, Audit and Anti-Fr"
short_description = "European Commissioner for European Commissioner for Economic" \
+ " and Monetary Affairs and the Euro|Ec..."
political_function = PoliticalFunction(position=position)
self.assertEquals(political_function.short_description, short_description)
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,783
|
CoSoECP/CoSo
|
refs/heads/master
|
/libs/time.py
|
from datetime import datetime
FORMAT = "%d %B %Y"
def to_datetime(date_string, date_format=FORMAT):
return datetime.strptime(date_string, date_format)
def french_format_to_datetime(date_string):
return datetime.strptime(date_string, "%d/%m/%Y")
def datetime_to_string(date, date_format=FORMAT):
"""
Converts datetime to string
"""
return date.strftime(date_format)
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,784
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/polls/migrations/0006_auto_20161214_2016.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-14 19:16
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('polls', '0005_auto_20161212_1908'),
]
operations = [
migrations.RenameField(
model_name='party',
old_name='creationDate',
new_name='creation_date',
),
]
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,785
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/polls/admin.py
|
from django.contrib import admin
from polls.models import Place, Candidate, Election, Result, \
TrendSource, Trend, Party, PoliticalFunction, Role, \
DetailedResults
class CandidateAdmin(admin.ModelAdmin):
fields = ('name', 'surname', 'birth_date', 'birth_place', 'nationality', 'image_url')
list_display = fields
class ElectionAdmin(admin.ModelAdmin):
fields = ('name', 'date', 'place',)
list_display = fields
class PlaceAdmin(admin.ModelAdmin):
fields = ('country', 'region', 'department', 'county', 'city')
list_display = fields
class ResultAdmin(admin.ModelAdmin):
fields = ('candidate', 'election', 'voting_result')
list_display = ('candidate', 'election_name', 'voting_result')
def election_name(self, obj):
return obj.election.print_name
class RoleAdmin(admin.ModelAdmin):
fields = ('candidate', 'short_position_type', 'election', 'beginning_date', 'end_date')
list_display = fields
def short_position_type(self, obj):
return obj.position_type.short_description
class TrendSourceAdmin(admin.ModelAdmin):
fields = ('name', 'grade')
list_display = fields
class TrendAdmin(admin.ModelAdmin):
fields = ('election', 'candidate', 'score', 'weight', 'trend_source', 'date', 'place')
list_display = ('election_name', 'candidate', 'score', 'weight', 'trend_source', 'date')
def election_name(self, obj):
return obj.election.print_name
admin.site.register(Candidate, CandidateAdmin)
admin.site.register(Election, ElectionAdmin)
admin.site.register(Place, PlaceAdmin)
admin.site.register(Result, ResultAdmin)
admin.site.register(Role, RoleAdmin)
admin.site.register(TrendSource, TrendSourceAdmin)
admin.site.register(Trend, TrendAdmin)
admin.site.register(Party)
admin.site.register(PoliticalFunction)
admin.site.register(DetailedResults)
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,786
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/polls/migrations/0003_election_candidates.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-12 11:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0002_auto_20161212_1217'),
]
operations = [
migrations.AddField(
model_name='election',
name='candidates',
field=models.ManyToManyField(through='polls.Result', to='polls.Candidate'),
),
]
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,787
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/import_data/views.py
|
# -*- coding: UTF-8 -*-
from coso.settings import WIKIPEDIA_BASE_API_URL, API_KEYS, GOOGLE_USERNAME, GOOGLE_PASSWORD
from polls.models import Candidate, Place, PoliticalFunction, Role, Trend, Election, Result, TrendSource
from libs.time import to_datetime
from libs import got
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.http import HttpResponseNotFound
from django.http import HttpResponse
from bs4 import BeautifulSoup
from datetime import datetime, time, timedelta
from json import load
from pytrends.request import TrendReq
from repustate import Client
from threading import Thread
import json
import logging
import os
import pandas
import requests
import sys
import tweepy
import urllib2
path = ""
@require_http_methods(["GET"])
def french_candidates(request):
# Only GET request will go that far
json_data = open('./static/french_politicians.json')
raw_data = json.load(json_data)
for raw_candidate in raw_data:
candidate = Candidate.objects.get_or_create(
name=raw_candidate["first_name"],
surname=raw_candidate["last_name"]
)
json_data.close()
return HttpResponse("Candidates import worked well")
@require_http_methods(["GET"])
def french_elections(request):
# Only GET request will go that far
_place, created = Place.objects.get_or_create(country="France", city="Paris")
json_data = open('./static/french_elections.json')
raw_data = json.load(json_data)
for raw_election in raw_data:
_election, created = Election.objects.get_or_create(
date = datetime(int(raw_election["annee"]), int(raw_election["mois"]), int(raw_election["jour"])),
place_id=_place.id,
name = raw_election["election"]
)
for raw_candidate in raw_election["resultats"]:
_candidate, created = Candidate.objects.get_or_create(
name=raw_candidate["name"],
surname=raw_candidate["surname"]
)
_result, created = Result.objects.get_or_create(
election_id = _election.id,
voting_result = raw_candidate["score"],
candidate_id = _candidate.id
)
json_data.close()
return HttpResponse("Elections and results import worked well")
@require_http_methods(["GET"])
def from_wikipedia(request):
"""
This method will get some information for each candidate in the DB from wikipedia
"""
candidates = Candidate.objects.all()
for candidate in candidates:
url = WIKIPEDIA_BASE_API_URL
url += candidate.name.replace(" ", "%20") + "%20"
url += candidate.surname.replace(" ", "%20")
response = requests.get(url)
if response.status_code == 200:
text = response.json()
page_id = text["query"]["pages"].keys()[0]
if page_id != "-1":
text = text["query"]["pages"][page_id]["revisions"][0]["*"]
starting_index = text.index("|name") if "|name" in text else text.index("birth_date")
text = text[starting_index + 1:]
# text.replace("=", "")
data = text.split("\n|")
data = clean_data(data)
process_wikipedia_data(candidate, data)
else:
logging.warning("Wikipedia info import for %s %s did not work"
% (candidate.name, candidate.surname))
return HttpResponse("Working on it")
def clean_data(data):
cleaned_data = {}
for element in data:
element = element.split()
starting_point = element.index("=") if "=" in element else 1
ending_point = element.index("\'\'\'") if "\'\'\'" in element else len(element)
value = " ".join(element[starting_point:ending_point])
value = value.replace("[", "")
value = value.replace("]", "")
value = value.replace("{", "")
value = value.replace("}", "")
cleaned_data[element[0]] = value
return cleaned_data
def process_birth_date(str_date):
# birth date and age|1954|8|12|df=y
start = str_date.index("|")
end = str_date.rindex("|")
date = str_date[start + 1:end]
date = date.split("|")
return datetime.date(int(date[0]), int(date[1]), int(date[2]))
def process_wikipedia_data(candidate, data):
if not candidate.birth_date and "birth_date" in data.keys():
try:
birth_date = process_birth_date(data["birth_date"])
candidate.birth_date = birth_date
except ValueError:
logging.warning("Value error on birth date")
if not candidate.birth_place and "birth_place" in data.keys():
birth_place = data["birth_place"].split(",")
place, created = Place.objects.get_or_create(country=" ".join(birth_place[1:]), city=birth_place[0])
candidate.birth_place_id = place.id
if not candidate.nationality and "nationality" in data.keys():
place, created = Place.objects.get_or_create(country=data["nationality"])
candidate.place_id = place.id
candidate.save()
# Save all the different roles for one candidate
roles = 0
while roles == 0 or "office%s" % (roles) in data.keys():
if roles == 0 and "office" in data.keys() or roles > 0:
position = data["office%s" % (roles)] if roles > 0 else data["office"]
if len(position) > 200:
position = position[:200]
political_function, created = PoliticalFunction.objects.get_or_create(position=position)
# Beginning date
beginning_date = None
if roles == 0 and "term_start" in data.keys() or roles > 0 and ("term_start%s" % (roles)) in data.keys():
field = "term_start%s" % (roles) if roles > 0 else "term_start"
start = data[field]
start = start.replace("=", "")
start = start.lstrip()
try:
beginning_date = to_datetime(start)
except ValueError:
beginning_date = None
# Ending date
end_date = None
if roles == 0 and "term_end" in data.keys() or roles > 0 and ("term_end%s" % (roles)) in data.keys():
field = "term_end%s" % (roles) if roles > 0 else "term_end"
end = data[field]
end = end.replace("=", "")
end = end.lstrip()
logging.warning(end)
try:
end_date = to_datetime(end)
except ValueError:
end_date = None
role, created = Role.objects.get_or_create(beginning_date=beginning_date, end_date=end_date,
position_type_id=political_function.id,
candidate_id=candidate.id)
roles += 1
"""
Code used to import data from sondage en france
"""
@require_http_methods(['GET'])
def sondage_2012(request):
wiki = "http://www.sondages-en-france.fr/sondages/Elections/Pr%C3%A9sidentielles%202012"
page = urllib2.urlopen(wiki)
soup = BeautifulSoup(page)
right_table = soup.find("table", class_= "summaryTable")
data = [[0 for x in range(14)] for y in range(12)]
k = 0
for row in right_table.findAll("tr"):
cells = row.findAll("td")
if len(cells) == 14:
for i in range(14):
data[k][i] = cells[i].get_text()
k += 1
if k > 11:
break
return HttpResponse("Hello, we've done the scrapping for 2012")
@require_http_methods(['GET'])
def sondage_2007(request):
wiki = "https://fr.wikipedia.org/wiki/%C3%89lection_pr%C3%A9sidentielle_fran%C3%A7aise_de_2007"
page = urllib2.urlopen(wiki)
soup = BeautifulSoup(page)
right_table = soup.find("table", class_="wikitable centre", style="text-align:center; font-size:95%;line-height:14px;")
data = [[0 for x in range(6)] for y in range(17)]
k = 1
data[0][0] = "Institution"
data[0][1] = "Date"
data[0][2] = "Sarkozy"
data[0][3] = "Royal"
data[0][4] = "Bayrou"
data[0][5] = "Le Pen"
d = {"Sarkozy": 2, "Royal": 3, "Bayrou": 4, "Le Pen": 5}
for row in right_table.findAll("tr"):
cells = row.findAll("td")
if len(cells) == 5:
data[k][0] = cells[0].get_text()
data[k][1] = cells[1].get_text()
for b_tag in cells[4].findAll("b"):
if b_tag.get_text() in d:
data[k][d[b_tag.get_text()]] = b_tag.findNext("b").get_text()
for a_tag in cells[4].findAll("a", recursive=False):
if a_tag.get_text() in d:
data[k][d[a_tag.get_text()]] = a_tag.next_sibling.replace(" | ", "").replace(" ", "")
k += 1
return HttpResponse("Hello, we've done the scrapping for 2007")
@require_http_methods(['GET'])
def sondage_2002(request):
wiki = "http://www.france-politique.fr/sondages-electoraux-presidentielle-2002.htm"
page = urllib2.urlopen(wiki)
soup = BeautifulSoup(page)
dataset = []
for table in soup.findAll("table"):
t = Thread(target= scrap_table, args=(table,dataset))
t.start()
return HttpResponse("Hello, we've done the scraping for 2002")
def scrap_table(table,dataset):
r = table.find("tr")
l = len(r.findAll("td"))
data = [[0 for x in range(l)] for y in range(17)]
k = 0
for row in table.findAll("tr"):
cells = row.findAll("td")
if len(cells) == l:
for i in range(l):
data[k][i] = cells[i].get_text().replace("\n ", "")
k += 1
if k > 16:
break
dataset.append(data)
return dataset
"""
Code used to import data from Twitter
"""
non_usable_keys=[]
def get_trends(request):
start_date = "2017-01-18"
end_date = "2017-01-19"
tag = "PrimaireGauche"
election_id = 6
get_twitter_trends(request, start_date, end_date, tag, election_id)
return HttpResponse("It worked thanks !")
def get_twitter_trends(request, election_id, start_date, end_date, tag):
try:
election = Election.objects.get(id=election_id)
except Election.DoesNotExist:
return HttpResponseNotFound("Candidate not found")
start = datetime.strptime(start_date, '%Y_%m_%d')
end = datetime.strptime(end_date, '%Y_%m_%d')
user_token = 0
while start < end:
save_to_database(start, tag, election)
start += timedelta(1)
def replace_api_key(not_working_api_key):
if not_working_api_key != '':
non_usable_keys.append(not_working_api_key)
for key in API_KEYS:
if key in non_usable_keys:
pass
else:
return key
def get_tweets_by_day_from_got(date, tag):
next_date = date + timedelta(days=1)
day = date.strftime('%Y-%m-%d')
next_day = next_date.strftime('%Y-%m-%d')
tweetCriteria = got.manager.TweetCriteria().setQuerySearch(tag).setSince(day).setUntil(next_day)
tweets = got.manager.TweetManager.getTweets(tweetCriteria)
return tweets
def filter_tweets_by_day_from_got(tweets, date, election):
api_key = replace_api_key('')
filtered_list = []
for tweet in tweets:
text = tweet.text
for candidate in election.candidates.all():
# On parcourt l'ensemble des candidats associés à l'objet election
if text.find(candidate.surname) != -1:
filtered_tweet = (date, text, candidate, get_score(text, api_key))
filtered_list.append(filtered_tweet)
return filtered_list
def get_score(text, api_key):
client = Client(api_key=api_key, version='v3')
text = text.encode("utf-8")
sentiment = client.sentiment(text, lang='fr')
if sentiment['status'] == 'OK':
return sentiment['score']
else:
get_score(text, replace_api_key(api_key))
def aggregate_by_day(filtered_list, day, election):
result = {}
final_result = []
for tweet in filtered_list:
add_value(result, tweet[2], tweet[3])
place, created = Place.objects.get_or_create(country = 'France', city="Paris")
twitter, twitter_created = TrendSource.objects.get_or_create(name="Twitter")
index = 0
for candidate in result:
trend = Trend(
place_id = place.id,
date = day,
election_id = election.id,
candidate_id = candidate.id,
score = round(result[candidate]['score'] / result[candidate]['weight'], 2),
weight = round(result[candidate]['weight'], 2),
trend_source_id = twitter.id
)
trend.save()
def add_value(dictionary, candidate, score):
if candidate not in dictionary:
dictionary[candidate] = {
'score': float(score),
'weight': 1
}
else:
dictionary[candidate]['score'] += float(score)
dictionary[candidate]['weight'] += 1
def save_to_database(day, tag, election):
"""
::param day: datetime
"""
tweets = get_tweets_by_day_from_got(day, tag)
filtered_list = filter_tweets_by_day_from_got(tweets, day, election)
aggregate_by_day(filtered_list, day, election)
"""
Code used to import data from Google Trends
"""
def import_trends(request_content):
vecteur = request_content[0]
pays = request_content[1]
date = request_content[2]
# connect to Google
pytrend = TrendReq(GOOGLE_USERNAME, GOOGLE_PASSWORD, custom_useragent='My Coso Script')
trend_payload = {'q': vecteur, 'hl': 'fr-FR', 'geo': pays,'date': date + ' 2m'}
# trend
trend = pytrend.trend(trend_payload)
df = pytrend.trend(trend_payload, return_type='dataframe')
return(df)
def analysis_from_google(request, election_id):
elections = [Election.objects.get(id=election_id)]
_google_trends, created = TrendSource.objects.get_or_create(name = "Google Trends")
total = 0.00
data=[]
for election in elections:
request_content = []
liste_candidat = []
candidats=election.candidates.order_by('result')
for candidat in candidats[:5]:
liste_candidat.append(candidat.surname + " " + candidat.name)
vecteur_candidat=", ".join(liste_candidat)
date=election.date
mois = date.month
annee=date.year
date_temp=[str(mois),str(annee)]
date_format="/".join(date_temp)
request_content.append(vecteur_candidat)
request_content.append("FR")
request_content.append(date_format)
my_data = import_trends(request_content)
for daily_date in my_data.index:
total = 0
for candidate in candidats[:5]:
candidate_name = candidate.surname + " " + candidate.name
if (isinstance(my_data.loc[daily_date, candidate_name.lower()], (int, float, long))):
candidate_weight = round(float(my_data.loc[daily_date, candidate_name.lower()]),2)
total = total + candidate_weight
for candidate in candidats[:5]:
candidate_name = candidate.surname + " " + candidate.name
if (total !=0 and str(total) != "nan"):
_trend, created = Trend.objects.get_or_create(place_id = election.place.id, date = pandas.to_datetime(daily_date), election_id = election.id, candidate_id = candidate.id, score = round(candidate_weight/total,2), weight = candidate_weight, trend_source_id = _google_trends.id)
return HttpResponse("Hello, we've done the Google Analysis")
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,788
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/polls/migrations/0005_auto_20161212_1908.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-12 18:08
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('polls', '0004_party_parent'),
]
operations = [
migrations.RenameModel(
old_name='Position',
new_name='PoliticalFunction',
),
migrations.RenameField(
model_name='detailedresults',
old_name='voteNumber',
new_name='vote_number',
),
migrations.RenameField(
model_name='party',
old_name='year_in_school',
new_name='political_orientation',
),
migrations.RenameField(
model_name='poll',
old_name='pollInstitute',
new_name='poll_institute',
),
migrations.RenameField(
model_name='result',
old_name='votingResult',
new_name='voting_result',
),
migrations.RenameField(
model_name='role',
old_name='positionType',
new_name='position_type',
),
migrations.RemoveField(
model_name='candidate',
name='birthDate',
),
migrations.RemoveField(
model_name='candidate',
name='birthPlace',
),
migrations.RemoveField(
model_name='role',
name='beginningDate',
),
migrations.RemoveField(
model_name='role',
name='endDate',
),
migrations.AddField(
model_name='candidate',
name='birth_date',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AddField(
model_name='candidate',
name='birth_place',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='polls.Place'),
),
migrations.AddField(
model_name='role',
name='beginning_date',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AddField(
model_name='role',
name='end_date',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AlterField(
model_name='election',
name='date',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AlterField(
model_name='party',
name='creationDate',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AlterField(
model_name='poll',
name='date',
field=models.DateTimeField(blank=True, null=True),
),
]
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,789
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/twitter/functions.py
|
from datetime import time
import datetime
import tweepy
from polls/models.py import Trend, Place, Election, Candidate
def different_classes():
_place, created = Place.objects.get_or_create(country="France")
_election, created = Election.objects.get_or_create(date=datetime.datetime(2016,12,22), place_id = _place.id)
_valls, created = Candidate.objects.get_or_create(name="Valls", surname = "Manuel", birth_date=datetime.datetime(1968,12,05), birth_place_id= _place.id, nationality_id= _place.id)
_montebourg, created = Candidate.objects.get_or_create(name="Montebourg", surname = "Arnaud", birth_place_id= _place.id, nationality_id= _place.id)
_hamon, created = Candidate.objects.get_or_create(name="Hamon", surname = "Benoit", nationality_id= _place.id)
_bennahmias, created = Candidate.objects.get_or_create(name="Bennahmias", surname = "Jean-Luc", nationality_id= _place.id)
_de_rugy, created = Candidate.objects.get_or_create(name="De Rugy", surname = "François", nationality_id= _place.id)
_pinel, created = Candidate.objects.get_or_create(name="Pinel", surname = "Sylvia", nationality_id= _place.id)
_peillon, created = Candidate.objects.get_or_create(name="Peillon", surname = "Vincent", birth_date=datetime.datetime(1968,12,05), birth_place_id= _place.id, nationality_id= _place.id)
_result1, created = Result.objects.get_or_create(election_id = _election.id, candidate_id = _candidate1.id)
_result2, created = Result.objects.get_or_create(election_id = _election.id, candidate_id = _candidate2.id)
_twitter, created = TrendSource.objects.get_or_create(name = 'Twitter')
def candidate_list():
candidates =[
]
def get_tweets_by_day(day, tag):
from json import load
filename = "./static/access.json"
with open(filename) as file:
token = load(file)
auth = tweepy.OAuthHandler(token[0]["consumer_key"], token[0]["consumer_secret"])
auth.set_access_token(token[0]["access_key"], token[0]["access_secret"])
api = tweepy.API(auth, wait_on_rate_limit=True)
date = datetime.datetime.strptime(day, '%Y-%m-%d')
next_date = date + datetime.timedelta(days=1)
next_day = next_date.strftime('%Y-%m-%d')
return tweepy.Cursor(api.search, q=tag, since=day,
until=next_day).items(25)
def filter_tweets_by_day(tweets, day, list_of_candidate_names):
api_key = replace_api_key('')
filtered_list = []
while True:
try:
tweet = tweets.next()
text = tweet.text
print(tweet.created_at)
for candidate in list_of_candidate_names:
if text.find(candidate) != -1:
filtered_tweet = {
'created_at': day,
'text': text,
'candidate': candidate,
'score': get_score(text, api_key)
}
filtered_list.append(filtered_tweet)
except tweepy.TweepError:
print('rate limit raised !')
time.sleep(60 * 15)
continue
except StopIteration:
break
return filtered_list
def get_score(text, api_key):
from repustate import Client
client = Client(api_key=api_key, version='v3')
sentiment = client.sentiment(text, lang='fr')
if sentiment['status'] == 'OK':
return sentiment['score']
else:
get_score(text, replace_api_key(api_key))
def aggregate_by_day(filtered_list, day):
result = {}
final_result = []
for tweet in filtered_list:
add_value(result, tweet['candidate'], tweet['score'])
for candidate in result:
trend = Trend.objects.get_or_create(
place_id = place.id
date = datetime.datetime.strptime(day, '%Y-%m-%d'),
election = election.id
candidate = candidate,
score = result[candidate]['score'] / result[candidate]['weight'],
weight = result[candidate]['weight'],
trend_source = twitter.id
)
# final_result.append(
# {
# 'place': 'France',
# 'date': datetime.datetime.strptime(day, '%Y-%m-%d'),
# 'election': 'Primaire socialiste 2017',
# 'candidate': candidate,
# 'score': result[candidate]['score'] / result[candidate]['weight'],
# 'weight': result[candidate]['weight'],
# 'trend_source': 'Twitter'
# }
# )
# #with open('data.json', 'w') as f:
# # json.dump(final_result, f, ensure_ascii=False)
# return final_result
def add_value(dict, candidate, score):
if candidate not in dict:
dict[candidate] = {
'score': float(score),
'weight': 1
}
else:
dict[candidate]['score'] += float(score)
dict[candidate]['weight'] += 1
def produce_json(day, tag):
list_of_candidate_names = {"valls", "montebourg", "hamon"}
tweets = get_tweets_by_day(day, tag)
filtered_list = filter_tweets_by_day(tweets, day, list_of_candidate_names)
return aggregate_by_day(filtered_list, day)
def replace_api_key(api_key):
return '6c8f03dbdd7fd059f44f365bf8eca282dd5f214c'
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,790
|
CoSoECP/CoSo
|
refs/heads/master
|
/coso/polls/migrations/0012_auto_20170212_2230.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-02-12 22:30
from __future__ import unicode_literals
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('polls', '0011_candidate_party'),
]
operations = [
migrations.CreateModel(
name='Statistics',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('score', models.DecimalField(decimal_places=3, max_digits=4)),
('start_date', models.DateTimeField(blank=True, null=True)),
('end_date', models.DateTimeField(blank=True, null=True)),
],
),
migrations.AddField(
model_name='candidate',
name='image_url',
field=models.TextField(blank=True, null=True, validators=[django.core.validators.URLValidator()]),
),
migrations.AddField(
model_name='election',
name='name',
field=models.CharField(blank=True, max_length=50, null=True),
),
migrations.AddField(
model_name='statistics',
name='candidate',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Candidate'),
),
migrations.AddField(
model_name='statistics',
name='election',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Election'),
),
migrations.AddField(
model_name='statistics',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
|
{"/coso/polls/views.py": ["/libs/time.py"], "/coso/polls/models.py": ["/libs/time.py"], "/coso/import_data/views.py": ["/libs/time.py"]}
|
21,799
|
mansi1597/Heart-disease-prediction
|
refs/heads/master
|
/predict_risk/urls.py
|
from django.conf.urls import url
from . import views
app_name='predict'
urlpatterns=[
url(r'^(?P<pk>\d+)$',views.PredictRisk,name='predict')
]
|
{"/predict_risk/views.py": ["/predict_risk/forms.py"], "/predict_risk/admin.py": ["/predict_risk/models.py"], "/predict_risk/forms.py": ["/predict_risk/models.py"]}
|
21,800
|
mansi1597/Heart-disease-prediction
|
refs/heads/master
|
/predict_risk/views.py
|
import csv,io
from django.shortcuts import render
from .forms import Predict_Form
from predict_risk.data_provider import *
from accounts.models import UserProfileInfo
from django.shortcuts import get_object_or_404, redirect, render
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required,permission_required
from django.urls import reverse
from django.contrib import messages
@login_required(login_url='/')
def PredictRisk(request,pk):
predicted = False
predictions={}
if request.session.has_key('user_id'):
u_id = request.session['user_id']
if request.method == 'POST':
form = Predict_Form(data=request.POST)
profile = get_object_or_404(UserProfileInfo, pk=pk)
if form.is_valid():
features = [[ form.cleaned_data['age'], form.cleaned_data['sex'], form.cleaned_data['cp'], form.cleaned_data['resting_bp'], form.cleaned_data['serum_cholesterol'],
form.cleaned_data['fasting_blood_sugar'], form.cleaned_data['resting_ecg'], form.cleaned_data['max_heart_rate'], form.cleaned_data['exercise_induced_angina'],
form.cleaned_data['st_depression'], form.cleaned_data['st_slope'], form.cleaned_data['number_of_vessels'], form.cleaned_data['thallium_scan_results']]]
standard_scalar = GetStandardScalarForHeart()
features = standard_scalar.transform(features)
SVCClassifier,LogisticRegressionClassifier,NaiveBayesClassifier,DecisionTreeClassifier=GetAllClassifiersForHeart()
predictions = {'SVC': str(SVCClassifier.predict(features)[0]),
'LogisticRegression': str(LogisticRegressionClassifier.predict(features)[0]),
'NaiveBayes': str(NaiveBayesClassifier.predict(features)[0]),
'DecisionTree': str(DecisionTreeClassifier.predict(features)[0]),
}
pred = form.save(commit=False)
l=[predictions['SVC'],predictions['LogisticRegression'],predictions['NaiveBayes'],predictions['DecisionTree']]
count=l.count('1')
result=False
if count>=2:
result=True
pred.num=1
else:
pred.num=0
pred.profile = profile
pred.save()
predicted = True
colors={}
if predictions['SVC']=='0':
colors['SVC']="table-success"
elif predictions['SVC']=='1':
colors['SVC']="table-danger"
if predictions['LogisticRegression']=='0':
colors['LR']="table-success"
else:
colors['LR']="table-danger"
if predictions['NaiveBayes']=='0':
colors['NB']="table-success"
else:
colors['NB']="table-danger"
if predictions['DecisionTree']=='0':
colors['DT']="table-success"
else:
colors['DT']="table-danger"
if predicted:
return render(request, 'predict.html',
{'form': form,'predicted': predicted,'user_id':u_id,'predictions':predictions,'result':result,'colors':colors})
else:
form = Predict_Form()
return render(request, 'predict.html',
{'form': form,'predicted': predicted,'user_id':u_id,'predictions':predictions})
|
{"/predict_risk/views.py": ["/predict_risk/forms.py"], "/predict_risk/admin.py": ["/predict_risk/models.py"], "/predict_risk/forms.py": ["/predict_risk/models.py"]}
|
21,801
|
mansi1597/Heart-disease-prediction
|
refs/heads/master
|
/predict_risk/migrations/0001_initial.py
|
# Generated by Django 2.1.7 on 2019-02-27 13:01
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Predictions',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('age', models.IntegerField()),
('sex', models.IntegerField(choices=[(0, 'Female'), (1, 'Male')], default=0)),
('cp', models.IntegerField(choices=[(1, 'Typical Angina'), (2, 'Atypical Angina'), (3, 'Non-Angina'), (4, 'Asymptomatic')], default=1)),
('resting_bp', models.IntegerField()),
('serum_cholesterol', models.IntegerField()),
('fasting_blood_sugar', models.IntegerField(choices=[(1, 'true'), (2, 'false')], default=0)),
('resting_ecg', models.IntegerField(choices=[(0, 'Normal'), (1, 'Having ST-T wave abnormality'), (2, 'hypertrophy')], default=0)),
('max_heart_rate', models.IntegerField()),
('exercise_induced_angina', models.IntegerField(choices=[(0, 'No'), (1, 'Yes')], default=0)),
('st_depression', models.DecimalField(decimal_places=2, max_digits=4)),
('st_slope', models.IntegerField(choices=[(1, 'Upsloping'), (2, 'Flat'), (3, 'Down Sloping')])),
('number_of_vessels', models.IntegerField(choices=[(0, 'None'), (1, 'One'), (2, 'Two'), (3, 'Three')])),
('thallium_scan_results', models.IntegerField(choices=[(3, 'Normal'), (6, 'Fixed Defect'), (7, 'Reversible Defect')])),
('predicted_on', models.DateTimeField(default=django.utils.timezone.now)),
('num', models.IntegerField()),
('profile', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='predict', to='accounts.UserProfileInfo')),
],
),
]
|
{"/predict_risk/views.py": ["/predict_risk/forms.py"], "/predict_risk/admin.py": ["/predict_risk/models.py"], "/predict_risk/forms.py": ["/predict_risk/models.py"]}
|
21,802
|
mansi1597/Heart-disease-prediction
|
refs/heads/master
|
/predict_risk/machine_learning_models/logistic_regression.py
|
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
DIR='C:/Users/Mansi/Desktop/Heart_disease_prediction_project/predict_risk/machine_learning_models'
dataset = pd.read_csv(DIR+'/HealthData.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 13].values
#handling missing data
from sklearn.preprocessing import Imputer
imputer=Imputer(missing_values='NaN',strategy='mean',axis=0)
imputer=imputer.fit(X[:,11:13])
X[:,11:13]=imputer.transform(X[:,11:13])
#splitting dataset into training set and test set
from sklearn.model_selection import train_test_split
X_train,X_test,Y_train,Y_test=train_test_split(X,y,test_size=0.25)
#feature scaling
from sklearn.preprocessing import StandardScaler
sc_X=StandardScaler()
X_train=sc_X.fit_transform(X_train)
X_test=sc_X.transform(X_test)
#exploring the dataset
import matplotlib.pyplot as plt
def draw_histograms(dataframe, features, rows, cols):
fig=plt.figure(figsize=(20,20))
for i, feature in enumerate(features):
ax=fig.add_subplot(rows,cols,i+1)
dataframe[feature].hist(bins=20,ax=ax,facecolor='midnightblue')
ax.set_title(feature+" Distribution",color='DarkRed')
fig.tight_layout()
plt.show()
draw_histograms(dataset,dataset.columns,6,3)
dataset.num.value_counts()
import seaborn as sn
sn.countplot(x='num',data=dataset)
#VISULAIZATIONS----relationship between attributes
pd.crosstab(dataset.thal,dataset.num).plot(kind='bar')
plt.title('bar chart for thal vs num')
plt.xlabel('thal')
plt.ylabel('num')
pd.crosstab(dataset.trestbps,dataset.num).plot(kind='bar')
plt.title('bar chart for trestbps vs num')
plt.xlabel('trestbps')
plt.ylabel('num')
pd.crosstab(dataset.cp,dataset.num).plot(kind='bar')
plt.title('bar chart for cp vs num')
plt.xlabel('cp')
plt.ylabel('num')
pd.crosstab(dataset.chol,dataset.num).plot(kind='bar')
plt.title('bar chart for chol vs num')
plt.xlabel('chol')
plt.ylabel('num')
pd.crosstab(dataset.restecg,dataset.num).plot(kind='bar')
plt.title('bar chart for restecg vs num')
plt.xlabel('restecg')
plt.ylabel('num')
####------------similarly can be seen for all the attributes------------------
#### logistic regression
#fitting LR to training set
from sklearn.linear_model import LogisticRegression
classifier =LogisticRegression()
classifier.fit(X_train,Y_train)
#Saving the model to disk
#from sklearn.externals import joblib
#filename = 'Logistic_regression_model.pkl'
#joblib.dump(classifier,filename)
#Predict the test set results
y_Class_pred=classifier.predict(X_test)
#checking the accuracy for predicted results
from sklearn.metrics import accuracy_score
accuracy_score(Y_test,y_Class_pred)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(Y_test, y_Class_pred)
#Interpretation:
from sklearn.metrics import classification_report
print(classification_report(Y_test, y_Class_pred))
#ROC
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
logit_roc_auc = roc_auc_score(Y_test, classifier.predict(X_test))
fpr, tpr, thresholds = roc_curve(Y_test, classifier.predict_proba(X_test)[:,1])
plt.figure()
plt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % logit_roc_auc)
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic')
plt.legend(loc="lower right")
plt.savefig('Log_ROC')
plt.show()
##PREDICTION FOR NEW DATASET
Newdataset = pd.read_csv('newdata.csv')
ynew=classifier.predict(Newdataset)
|
{"/predict_risk/views.py": ["/predict_risk/forms.py"], "/predict_risk/admin.py": ["/predict_risk/models.py"], "/predict_risk/forms.py": ["/predict_risk/models.py"]}
|
21,803
|
mansi1597/Heart-disease-prediction
|
refs/heads/master
|
/predict_risk/models.py
|
from django.db import models
from accounts.models import UserProfileInfo
from django.utils import timezone
from django.urls import reverse
# Create your models here.
sex_choices=((0, 'Female'),(1, 'Male'))
cp_choice=((0,'None'),(1, 'Typical Angina'),(2, 'Atypical Angina'),(3, 'Non-Angina'),(4, 'Asymptomatic'))
fasting_blood_sugar_choices=((1,'> 120 mg/dl'),((0,'< 120 mg/dl')))
resting_ecg_choices=((0, 'Normal'),(1, 'Having ST-T wave abnormality'),(2, 'hypertrophy'))
exercise_induced_angina_choices=((0, 'No'),(1, 'Yes'))
st_slope_choices=((1, 'Upsloping'),(2, 'Flat'),(3, 'Down Sloping'))
number_of_vessels_choices=((0, 'None'),(1, 'One'),(2, 'Two'),(3, 'Three'))
thallium_scan_results_choices=((3, 'Normal'),(6, 'Fixed Defect'),(7, 'Reversible Defect'))
class Predictions(models.Model):
profile = models.ForeignKey(UserProfileInfo, on_delete=models.CASCADE, related_name='predict')
age = models.IntegerField()
sex = models.IntegerField(choices=sex_choices, default=0)
cp = models.IntegerField(choices=cp_choice,default=0)
resting_bp = models.IntegerField()
serum_cholesterol = models.IntegerField()
fasting_blood_sugar = models.IntegerField(choices=fasting_blood_sugar_choices,default=0)
resting_ecg = models.IntegerField(choices=resting_ecg_choices,default=0)
max_heart_rate = models.IntegerField()
exercise_induced_angina = models.IntegerField(choices=exercise_induced_angina_choices,default=0)
st_depression = models.DecimalField(max_digits=4, decimal_places=2)
st_slope = models.IntegerField(choices=st_slope_choices)
number_of_vessels = models.IntegerField(choices=number_of_vessels_choices)
thallium_scan_results = models.IntegerField(choices=thallium_scan_results_choices)
predicted_on = models.DateTimeField(default=timezone.now)
num=models.IntegerField()
def get_absolute_url(self):
return reverse('predict:predict', kwargs={'pk': self.profile.pk})
|
{"/predict_risk/views.py": ["/predict_risk/forms.py"], "/predict_risk/admin.py": ["/predict_risk/models.py"], "/predict_risk/forms.py": ["/predict_risk/models.py"]}
|
21,804
|
mansi1597/Heart-disease-prediction
|
refs/heads/master
|
/predict_risk/migrations/0002_auto_20190228_2016.py
|
# Generated by Django 2.1.7 on 2019-02-28 14:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('predict_risk', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='predictions',
name='fasting_blood_sugar',
field=models.IntegerField(choices=[(1, '> 120 mg/dl'), (0, '< 120 mg/dl')], default=0),
),
]
|
{"/predict_risk/views.py": ["/predict_risk/forms.py"], "/predict_risk/admin.py": ["/predict_risk/models.py"], "/predict_risk/forms.py": ["/predict_risk/models.py"]}
|
21,805
|
mansi1597/Heart-disease-prediction
|
refs/heads/master
|
/predict_risk/admin.py
|
from django.contrib import admin
from predict_risk.models import Predictions
from django import forms
class Prediction(admin.ModelAdmin):
list_display=('profile','age','sex','cp','resting_bp','bloodcholesterol','fasting_blood_sugar','resting_ecg','max_heart_rate','exercise_induced_angina','st_depression','st_slope','number_of_vessels','thallium_scan_results','predicted_on','num')
admin.site.register(Predictions,Prediction)
# Register your models here.
|
{"/predict_risk/views.py": ["/predict_risk/forms.py"], "/predict_risk/admin.py": ["/predict_risk/models.py"], "/predict_risk/forms.py": ["/predict_risk/models.py"]}
|
21,806
|
mansi1597/Heart-disease-prediction
|
refs/heads/master
|
/predict_risk/machine_learning_models/decision_tree.py
|
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('HealthData.csv')
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:, 13].values
#handling missing data
from sklearn.preprocessing import Imputer
imputer=Imputer(missing_values='NaN',strategy='mean',axis=0)
imputer=imputer.fit(X[:,11:13])
X[:,11:13]=imputer.transform(X[:,11:13])
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.15, random_state = 0)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
#EXPLORING THE DATASET
import seaborn as sn
sn.countplot(x='num',data=dataset)
dataset.num.value_counts()
# Fitting Decision Tree Classification to the Training set
from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)
classifier.fit(X_train, y_train)
from sklearn.externals import joblib
filename = 'decision_tree_model.pkl'
joblib.dump(classifier,filename)
# Predicting the Test set results
y_pred = classifier.predict(X_test)
#ACCURACY SCORE
from sklearn.metrics import accuracy_score
accuracy_score(y_test,y_pred)
##CONFUSION MATRIX
from sklearn.metrics import classification_report, confusion_matrix
cm=confusion_matrix(y_test, y_pred)
#Interpretation:
from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred))
#ROC
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
logit_roc_auc = roc_auc_score(y_test, classifier.predict(X_test))
fpr, tpr, thresholds = roc_curve(y_test, classifier.predict_proba(X_test)[:,1])
plt.figure()
plt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % logit_roc_auc)
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic')
plt.legend(loc="lower right")
plt.savefig('Log_ROC')
plt.show()
##PREDICTION FOR NEW DATASET
Newdataset = pd.read_csv('newdata.csv')
ynew=classifier.predict(Newdataset)
|
{"/predict_risk/views.py": ["/predict_risk/forms.py"], "/predict_risk/admin.py": ["/predict_risk/models.py"], "/predict_risk/forms.py": ["/predict_risk/models.py"]}
|
21,807
|
mansi1597/Heart-disease-prediction
|
refs/heads/master
|
/accounts/views.py
|
from django.shortcuts import render
from .forms import UserForm, UserProfileInfoForm, UpdateProfileForm
from django.views.generic import DetailView,UpdateView,TemplateView
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from .models import UserProfileInfo, User
from django.shortcuts import get_object_or_404
# Create your views here.
@login_required
def user_logout(request):
#del request.session['user_id']
request.session.flush()
logout(request)
return HttpResponseRedirect(reverse('user_login'))
class Aboutpageview(TemplateView):
template_name='accounts/about.html';
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileInfoForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
print(user_form.errors, profile_form.errors)
if registered:
return HttpResponseRedirect(reverse('user_login'))
else:
user_form = UserForm()
profile_form = UserProfileInfoForm()
return render(request, 'accounts/register.html',
{'user_form': user_form, 'profile_form': profile_form, 'registered': registered})
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
request.session['user_id'] = user.profile.pk
return HttpResponseRedirect(reverse('predict:predict', kwargs={'pk': user.profile.pk}))
else:
return HttpResponse("Account not active")
else:
print("Tried login and failed")
print("username: {} and password: {}".format(username, password))
return HttpResponse("Invalid login details supplied!")
else:
return render(request, 'accounts/login.html', {})
class ProfileDetailView(LoginRequiredMixin, DetailView):
login_url = '/'
redirect_field_name = '/'
model = UserProfileInfo
template_name = 'accounts/profileview.html'
def get_context_data(self, **kwargs):
if self.request.session.has_key('user_id'):
u_id = self.request.session['user_id']
context = super(ProfileDetailView, self).get_context_data(**kwargs)
context['user_id'] = u_id
return context
|
{"/predict_risk/views.py": ["/predict_risk/forms.py"], "/predict_risk/admin.py": ["/predict_risk/models.py"], "/predict_risk/forms.py": ["/predict_risk/models.py"]}
|
21,808
|
mansi1597/Heart-disease-prediction
|
refs/heads/master
|
/predict_risk/migrations/0003_auto_20190228_2026.py
|
# Generated by Django 2.1.7 on 2019-02-28 14:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('predict_risk', '0002_auto_20190228_2016'),
]
operations = [
migrations.AlterField(
model_name='predictions',
name='cp',
field=models.IntegerField(choices=[(0, 'None'), (1, 'Typical Angina'), (2, 'Atypical Angina'), (3, 'Non-Angina'), (4, 'Asymptomatic')], default=0),
),
]
|
{"/predict_risk/views.py": ["/predict_risk/forms.py"], "/predict_risk/admin.py": ["/predict_risk/models.py"], "/predict_risk/forms.py": ["/predict_risk/models.py"]}
|
21,809
|
mansi1597/Heart-disease-prediction
|
refs/heads/master
|
/predict_risk/forms.py
|
from django import forms
from predict_risk.models import Predictions
class Predict_Form(forms.ModelForm):
class Meta:
model = Predictions
fields = ('age','sex','cp','resting_bp','serum_cholesterol','fasting_blood_sugar','resting_ecg','max_heart_rate',
'exercise_induced_angina','st_depression','st_slope','number_of_vessels','thallium_scan_results')
widgets = {'age': forms.TextInput(attrs={'class': 'form-control'}),
'sex': forms.Select(attrs={'class': 'form-control'}),
'cp': forms.Select(attrs={'class': 'form-control'}),
'resting_bp':forms.TextInput(attrs={'class': 'form-control'}),
'serum_cholesterol':forms.TextInput(attrs={'class': 'form-control'}),
'fasting_blood_sugar':forms.Select(attrs={'class': 'form-control'}),
'resting_ecg':forms.Select(attrs={'class': 'form-control'}),
'max_heart_rate':forms.TextInput(attrs={'class': 'form-control'}),
'exercise_induced_angina':forms.Select(attrs={'class': 'form-control'}),
'st_depression':forms.TextInput(attrs={'class': 'form-control'}),
'st_slope':forms.Select(attrs={'class': 'form-control'}),
'number_of_vessels':forms.Select(attrs={'class': 'form-control'}),
'thallium_scan_results':forms.Select(attrs={'class': 'form-control'}),
}
|
{"/predict_risk/views.py": ["/predict_risk/forms.py"], "/predict_risk/admin.py": ["/predict_risk/models.py"], "/predict_risk/forms.py": ["/predict_risk/models.py"]}
|
21,810
|
mansi1597/Heart-disease-prediction
|
refs/heads/master
|
/accounts/urls.py
|
from django.conf.urls import url
from . import views
app_name = 'accounts'
urlpatterns=[
url(r'^register/$', views.register, name='register'),
url(r'^logout/$',views.user_logout,name='logout'),
url(r'^profile/(?P<pk>\d+)/$', views.ProfileDetailView.as_view(), name='profile'),
#url(r'^profile/(?P<pk>\d+)/edit/$', views.profile_update, name='edit_profile'),
]
|
{"/predict_risk/views.py": ["/predict_risk/forms.py"], "/predict_risk/admin.py": ["/predict_risk/models.py"], "/predict_risk/forms.py": ["/predict_risk/models.py"]}
|
21,811
|
mansi1597/Heart-disease-prediction
|
refs/heads/master
|
/predict_risk/apps.py
|
from django.apps import AppConfig
class PredictRiskConfig(AppConfig):
name = 'predict_risk'
|
{"/predict_risk/views.py": ["/predict_risk/forms.py"], "/predict_risk/admin.py": ["/predict_risk/models.py"], "/predict_risk/forms.py": ["/predict_risk/models.py"]}
|
21,812
|
mansi1597/Heart-disease-prediction
|
refs/heads/master
|
/accounts/admin.py
|
from django.contrib import admin
from accounts.models import UserProfileInfo
class UserProfile(admin.ModelAdmin):
list_display = ('user', 'profile_pic')
admin.site.register(UserProfileInfo,UserProfile)
# Register your models here.
|
{"/predict_risk/views.py": ["/predict_risk/forms.py"], "/predict_risk/admin.py": ["/predict_risk/models.py"], "/predict_risk/forms.py": ["/predict_risk/models.py"]}
|
21,835
|
mahidulmoon/Protected-PortFolio
|
refs/heads/master
|
/portfolio219/portfolio/views.py
|
from django.shortcuts import render
from .models import Portfolio
# Create your views here.
def index(request):
if request.method=="POST":
name = request.POST['name']
email = request.POST['email']
contact = request.POST['phone']
msg = request.POST['msg']
obj=Portfolio(name=name,email=email,phone=contact,message=msg)
obj.save()
return render(request,"index.html",{})
|
{"/portfolio219/portfolio/views.py": ["/portfolio219/portfolio/models.py"]}
|
21,836
|
mahidulmoon/Protected-PortFolio
|
refs/heads/master
|
/portfolio219/portfolio/models.py
|
from django.db import models
class Portfolio(models.Model):
name=models.CharField(max_length=50)
email = models.CharField(max_length=50)
phone = models.CharField(max_length=50)
message = models.CharField(max_length=50)
|
{"/portfolio219/portfolio/views.py": ["/portfolio219/portfolio/models.py"]}
|
21,837
|
mahidulmoon/Protected-PortFolio
|
refs/heads/master
|
/portfolio219(django)/portfolio/views.py
|
from django.shortcuts import render
from .models import Portfolio
# Create your views here.
def index(request):
if request.method=="POST":
name = request.GET['name']
email = request.GET['email']
contact = request.GET['phone']
msg = request.GET['msg']
obj=Portfolio(name=name,email=email,phone=contact,message=msg)
obj.save()
return render(request,"index.html",{})
|
{"/portfolio219/portfolio/views.py": ["/portfolio219/portfolio/models.py"]}
|
21,846
|
GroundWu/EntDataCrawl
|
refs/heads/master
|
/dbService.py
|
import sqlite3
import time
class DBService:
def __init__(self):
self.conn = sqlite3.connect('ent.db')
self.cursor = self.conn.cursor()
self.creatTable()
def creatTable(self):
ent_table="create table if not exists entname(id integer primary key autoincrement,name varchar(20),regNo varchar(30),url varchar(256),time integer)"
enturls_table="create table if not exists enturl(id integer primary key autoincrement,regNO varchar(30) not null,urldict text not null,time integer)"
self.cursor.execute(ent_table)
self.cursor.execute(enturls_table)
self.conn.commit();
def insert(self,table,params):
sql1="insert into entname(name,regNo,url,time)values (?,?,?,?) "
sql2="insert into enturl(regNo,urldict,time) values(?,?,?)"
if table==1:
self.cursor.execute(sql1,params)
else:
self.cursor.execute(sql2,params)
self.conn.commit()
return self.cursor.rowcount
def query(self,table,params):
sql1="select url,time from entname where regNo=?"
sql2="select urldict from enturl where regNo=?"
if table==1:
self.cursor.execute(sql1,params)
else:
self.cursor.execute(sql2,params)
return self.cursor.fetchone()
def delete(self,table,params=()):
sql1="delete from entname where regNo=?"
sql2="delete from enturl where regNo=?"
sql3="delete from entname where time<?"
sql4="delete from enturl where time<?"
if table==1:
self.cursor.execute(sql1,params)
elif table==2:
self.cursor.execute(sql2,params)
else:
self.cursor.execute(sql3,params)
self.cursor.execute(sql4,params)
self.conn.commit()
return self.cursor.rowcount
def update(self,params):
pass
def __del__(self):
self.cursor.close()
self.conn.close()
# if __name__=="__main__":
# db = DBService()
# # db.insert(1,('a','b','c',int(time.time())))
# db.delete(3,(time.time(),))
# print(db.query(1,('b',)))
|
{"/entInfoApi.py": ["/hack.py", "/getInfo.py", "/dbService.py"], "/getInfo.py": ["/dbService.py"]}
|
21,847
|
GroundWu/EntDataCrawl
|
refs/heads/master
|
/entInfoApi.py
|
from flask import Flask,request,jsonify
from hack import spiderinfo
from getInfo import getInfo
import json
import time
from dbService import DBService
app = Flask(__name__)
prefix = '/entInfo/api/v1.0'
db = DBService()
@app.route(prefix+'/findEnt/<entName>',methods=['GET'])
def findEnt(entName):
db.delete(3,(time.time()-60,))
result=spiderinfo(entName)
return jsonify(result)
@app.route(prefix+'/basicInfo/<id>',methods=['GET'])
def basicInfo(id):
# db=DBService()
url=db.query(1,(id,))[0]
g=getInfo()
result=g.get_basic_info(url,id)
return jsonify(result)
@app.route(prefix+'/shareHolderInfo/<id>',methods=['GET'])
def shareHolderInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_holders_info(url_dict['shareholderUrl'])
return jsonify(result)
@app.route(prefix+'/keyPersonInfo/<id>',methods=['GET'])
def keyPersonInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_keyperson_info(url_dict['keyPersonUrl'])
return jsonify(result)
@app.route(prefix+'/branchGroupInfo/<id>',methods=['GET'])
def branchGroupInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_branchgroup_info(url_dict['branchUrl'])
return jsonify(result)
@app.route(prefix+'/liquidationInfo/<id>',methods=['GET'])
def liquidationInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_more_info(url_dict['liquidationUrl'])
return jsonify(result)
@app.route(prefix+'/alterInfo/<id>',methods=['GET'])
def alterInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_alter_info(url_dict['alterInfoUrl'])
return jsonify(result)
@app.route(prefix+'/mortRegInfo/<id>',methods=['GET'])
def mortRegInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_more_info(url_dict['mortRegInfoUrl'])
return jsonify(result)
@app.route(prefix+'/stakQualitInfo/<id>',methods=['GET'])
def stakQualitInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_more_info(url_dict['stakQualitInfoUrl'])
return jsonify(result)
@app.route(prefix+'/proPledgeRegInfo/<id>',methods=['GET'])
def proPledgeRegInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_more_info(url_dict['proPledgeRegInfoUrl'])
return jsonify(result)
@app.route(prefix+'/trademarkInfo/<id>',methods=['GET'])
def trademarkInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_more_info(url_dict['trademarkInfoUrl'])
return jsonify(result)
@app.route(prefix+'/spotCheckInfo/<id>',methods=['GET'])
def spotCheckInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_spotCheck_info(url_dict['spotCheckInfoUrl'])
return jsonify(result)
@app.route(prefix+'/assistInfo/<id>',methods=['GET'])
def assistInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_assist_info(url_dict['assistUrl'])
return jsonify(result)
@app.route(prefix+'/insLicenInfo/<id>',methods=['GET'])
def insLicenInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_insLicence_info(url_dict['insLicenceinfoUrl'])
return jsonify(result)
@app.route(prefix+'/insInvInfo/<id>',methods=['GET'])
def insInvInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_more_info(url_dict['insInvinfoUrl'])
return jsonify(result)
@app.route(prefix+'/insAlterstockInfo/<id>',methods=['GET'])
def insAlterstockInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_more_info(url_dict['insAlterstockinfoUrl'])
return jsonify(result)
@app.route(prefix+'/insProPledgeRegInfo/<id>',methods=['GET'])
def insProPledgeRegInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_more_info(url_dict['insProPledgeRegInfoUrl'])
return jsonify(result)
@app.route(prefix+'/insPunishmentInfo/<id>',methods=['GET'])
def insPunishmentInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_more_info(url_dict['insPunishmentinfoUrl'])
return jsonify(result)
@app.route(prefix+'/simpleCancelInfo/<id>',methods=['GET'])
def simpleCancelInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_more_info(url_dict['simpleCancelUrl'])
return jsonify(result)
@app.route(prefix+'/otherLicenceDetailInfo/<id>',methods=['GET'])
def otherLicenceDetailInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_more_info(url_dict['otherLicenceDetailInfoUrl'])
return jsonify(result)
@app.route(prefix+'/punishmentDetailInfo/<id>',methods=['GET'])
def punishmentDetailInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_more_info(url_dict['punishmentDetailInfoUrl'])
return jsonify(result)
@app.route(prefix+'/entBusExcep/<id>',methods=['GET'])
def entBusExcep(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_more_info(url_dict['entBusExcepUrl'])
return jsonify(result)
@app.route(prefix+'/illInfo/<id>',methods=['GET'])
def illInfo(id):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_more_info(url_dict['IllInfoUrl'])
return jsonify(result)
@app.route(prefix+'/anCheYearInfo/<id>/<year>',methods=['GET'])
def anCheYearInfo(id,year):
# db=DBService()
url_json=db.query(2,(id,))[0]
url_dict=json.loads(url_json)
g=getInfo()
result=g.get_anCheYear_info(url_dict['anCheYearInfo'])
return jsonify(result)
if __name__=="__main__":
app.run();
|
{"/entInfoApi.py": ["/hack.py", "/getInfo.py", "/dbService.py"], "/getInfo.py": ["/dbService.py"]}
|
21,848
|
GroundWu/EntDataCrawl
|
refs/heads/master
|
/getInfo.py
|
#-*-coding:utf-8-*-
import urllib.request
from urllib import parse
import re
import json
from bs4 import BeautifulSoup
import time
from dbService import DBService
class getInfo:
def __init__(self):
self.count=0
#发送请求
def get(self,url,postdata={}):
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}
postdata=parse.urlencode(postdata).encode('utf-8')
req=urllib.request.Request(url=url,headers=headers,data=postdata)
data=''
try:
res=urllib.request.urlopen(req,timeout=10)
data=res.read().decode('utf8')
print('No.'+str(self.count)+': '+url)
# print(data)
self.count+=1
except:
try:
res=urllib.request.urlopen(req,timeout=15)
data=res.read().decode('utf8')
print('Retry==>No.'+str(self.count)+': '+url)
except:
data='None'
# print(data)
finally:
if 'invalidLink' in data:
print('invalidLink...')
return data
#连续发送请求,获取分页数据
def post(self,url):
data_list=[]
postdata={}
totalPage=0
try:
jsondata=self.get(url,postdata)
jsondata=re.sub("<div .*?>.*?</div>|<span .*?>.*?</span>","",jsondata)
if jsondata!='':
data=json.loads(jsondata)
totalPage=data['totalPage']
perPage=data['perPage']
data_list.extend(data['data'])
except:
print('get post request failed! url:'+url)
else:
for page in range(totalPage-1):
postdata={}
postdata['draw']=page+1
postdata['start']=perPage*(page+1)
postdata['length']=perPage
try:
result=self.get(url,postdata)
result=re.sub("<div .*?>.*?</div>|<span .*?>.*?</span>","",result)
page_result=json.loads(result)['data']
except:
print('get page info failed! url:'+url)
print(result)
else:
data_list.extend(page_result)
time.sleep(0.1)
finally:
return data_list
#获取对应的信息url
def get_and_store_url(self,regNo):
host='http://www.gsxt.gov.cn'
soup=BeautifulSoup(self.html,'html.parser')
tag=soup.find(class_='mainContent')
s=tag.script.get_text()
url_dict=dict(re.findall(r'var\s+(\w+)\s+=\s+\"(.*)\"',s))
for k,v in url_dict.items():
url_dict[k]=host+v
db = DBService()
jsonstr=json.dumps(url_dict)
if db.query(2,(regNo,))==None:
db.insert(2,(regNo,jsonstr,time.time()))
return url_dict
#获取基本信息
def get_basic_info(self,url,regNo):
self.html=self.get(url)
self.url_dict=self.get_and_store_url(regNo)
soup=BeautifulSoup(self.html,"html.parser")
tag=soup.find(id='primaryInfo')
result=tag.find_all('dd')
values=[re.sub('[\s+\:\:\^]','',item.get_text()) for item in result]
items=tag.find_all('dt')
keys=[re.sub('[\s+\:\:\^]','',item.get_text()) for item in items]
primaryInfo=dict(zip(keys,values))
return primaryInfo
#获取股东及出资信息
def get_holders_info(self,url):
data=self.post(url)
holders_info=[]
try:
# print(data)
for item in data:
holder={}
holder['股东Id']=item['invId']
holder['股东名称']=item['inv']
holder['股东类型']=item['invType_CN']
holder['国籍']=item['country_CN']
holder['证照类型']=item['blicType_CN']
holder['证照号码']=item['bLicNo']
holder['证件类型']=item['cerType_CN']
holder['证件号码']=item['cerNo']
holder['详情']=self.get_holder_detail(item['invId'])
holders_info.append(holder)
except:
print("get holders info failed!")
finally:
return holders_info
#获取发起人及出资信息详情
def get_holder_detail(self,invId):
url='http://www.gsxt.gov.cn/corp-query-entprise-info-shareholderDetail-'+invId+'.html'
data=self.post(url)
return data
#获取主要人员信息
def get_keyperson_info(self,url):
data=self.post(url)
keyPersons=[]
try:
for item in data:
keyperson={}
keyperson['名称']=item['name']
keyperson['职位']=item['position_CN']+'(备注:生成的base64编码要删去换行符或回车符)'
keyPersons.append(keyperson)
except:
print('get key person info failed!')
finally:
return keyPersons
#分支管理机构信息
def get_branchgroup_info(self,url):
data=self.post(url)
branchgroups=[]
try:
for item in data:
branchgroup={}
branchgroup['名称']=item['brName']
branchgroup['统一社会信用代码/注册号']=item['regNo'].strip()
branchgroup['登记机关']=item['regOrg_CN']
branchgroups.append(branchgroup)
except:
print('get branchgroup info failed!')
finally:
return branchgroups
#获取变更信息
def get_alter_info(self,url):
data=self.post(url)
alterInfo=[]
try:
for item in data:
alterInfo_item={}
alterInfo_item['变更事项']=item['altItem_CN']
alterInfo_item['变更前内容']=item['altBe']
alterInfo_item['变更后内容']=item['altAf']
alterInfo_item['变更日期']=item['altDate']
alterInfo.append(alterInfo_item)
except:
print('get alter info failed!')
finally:
return alterInfo
#获取检查结果信息
def get_spotCheck_info(self,url):
data=self.post(url)
spotCheckInfo=[]
try:
for item in data:
spotCheckInfo_item={}
spotCheckInfo_item['检查实施机关']=item['insAuth_CN']
spotCheckInfo_item['类型']=item['insType']
spotCheckInfo_item['日期']=item['insDate']
spotCheckInfo_item['结果']=item['insRes_CN']
spotCheckInfo.append(spotCheckInfo_item)
except:
print('get spotCheck info failed!')
finally:
return spotCheckInfo
def get_insLicence_info(self,url):
data=self.post(url)
try:
for item in data:
id=item['licId']
url_1='http://www.gsxt.gov.cn/corp-query-entprise-info-insLicenceInfoForJs-'+id+'.html'
res_1=self.get(url_1)
res_1=json.loads(res_1)
url_2='http://www.gsxt.gov.cn'+res_1['insLicenceDetailInfoUrl']
res_2=self.get(url_2)
detail=json.loads(res_2)
item['detail']=detail
except:
print('get insLicence detail info failed!')
finally:
return data
def get_assist_info(self,url):
data=self.post(url)
try:
for item in data:
id=item['parent_Id']
url_1='http://www.gsxt.gov.cn/corp-query-entprise-info-judiciaryStockfreeze-'+id+'.html'
detail=self.post(url_1)
item['detail']=detail
except:
print('get assistInfo failed!')
finally:
return data
def get_more_info(self,url):
data=self.post(url)
# print(data)
return data
def get_anCheYear_info(self,url):
data=self.get(url)
anCheYearInfo=[]
try:
data=json.loads(data)
for item in data:
anCheYearInfo_item={}
anCheYearInfo_item['anCheYear']=item['anCheYear']
anCheYearInfo_item['anCheId']=item['anCheId']
anCheYearInfo_item['anCheDate']=item['anCheDate']
anCheYearInfo_item['anCheYearDetail']=self.get_anCheYear_Detail(item)
anCheYearInfo.append(anCheYearInfo_item)
except:
print('get anCheYear info failed!')
return anCheYearInfo
def get_anCheYear_Detail(self,item):
anCheId=item['anCheId']
prefix='http://www.gsxt.gov.cn/corp-query-entprise-info-'
#组装需要请求的url集合
urls={}
urls['baseinfo']=prefix+'baseinfo-'+anCheId+'.html'
urls['webSiteInfo']=prefix+'webSiteInfo-'+anCheId+'.html'
urls['forInvestment']=prefix+'forInvestment-'+anCheId+'.html'
urls['sponsor']=prefix+'sponsor-'+anCheId+'.html'
urls['vAnnualReportAlterstockinfo']=prefix+'vAnnualReportAlterstockinfo-'+anCheId+'.html'
urls['forGuaranteeinfo']=prefix+'forGuaranteeinfo-'+anCheId+'.html'
urls['AnnSocsecinfo']=prefix+'AnnSocsecinfo-'+anCheId+'.html'
urls['annualAlter']=prefix+'annualAlter-'+anCheId+'.html'
#生成结果字典
try:
result={key:self.post(url) for (key,url) in urls.items()}
except:
result={}
finally:
return result
# def run(self):
# result={}
# # 基础公示信息
# self.get_basic_info()
# self.get_holders_info(self.url_dict['shareholderUrl'])
# self.get_keyperson_info(self.url_dict['keyPersonUrl'])
# self.get_branchgroup_info(self.url_dict['branchUrl'])
# self.get_more_info(self.url_dict['liquidationUrl'])
# self.get_alter_info(self.url_dict['alterInfoUrl'])
# self.get_more_info(self.url_dict['mortRegInfoUrl'])
# self.get_more_info(self.url_dict['stakQualitInfoUrl'])
# self.get_more_info(self.url_dict['proPledgeRegInfoUrl'])
# self.get_more_info(self.url_dict['trademarkInfoUrl'])
# self.get_spotCheck_info(self.url_dict['spotCheckInfoUrl'])
# self.get_assist_info(self.url_dict['assistUrl'])
# #企业提供信息
# ##年报
# self.get_anCheYear_info(self.url_dict['anCheYearInfo'])
# self.get_insLicence_info(self.url_dict['insLicenceinfoUrl'])
# self.url_dict['insInvinfoUrl']
# self.url_dict['insAlterstockinfoUrl']
# self.url_dict['insProPledgeRegInfoUrl']
# self.url_dict['insPunishmentinfoUrl']
# self.url_dict['simpleCancelUrl']
# for (k,v) in enterprise_provide_info_url.items():
# enterprise_provide_info[k]=self.get_more_info(v)
# #行政许可信息
# self.get_more_info(self.url_dict['otherLicenceDetailInfoUrl'])
# #行政处罚信息
# self.get_more_info(self.url_dict['punishmentDetailInfoUrl'])
# #列入经营异常名录信息
# self.get_more_info(self.url_dict['entBusExcepUrl'])
# #列入严重违法失信企业名单(黑名单)信息
# self.get_more_info(self.url_dict['IllInfoUrl'])
|
{"/entInfoApi.py": ["/hack.py", "/getInfo.py", "/dbService.py"], "/getInfo.py": ["/dbService.py"]}
|
21,849
|
GroundWu/EntDataCrawl
|
refs/heads/master
|
/hack.py
|
import sys
import PIL.Image as image
import PIL.ImageChops as imagechops
import time,re,random
import io
import urllib.request
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
from getInfo import getInfo
from dbService import DBService
#获取浏览器驱动
def get_webdriver(name):
if name.lower() == "phantomjs":
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36")
return webdriver.PhantomJS(desired_capabilities=dcap)
elif name.lower() == "chrome":
return webdriver.Chrome(executable_path=r"C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe")
#输入查询词,点击按钮
def input_params(driver,name):
driver.get("http://www.gsxt.gov.cn/index")
element = WebDriverWait(driver,10).until(lambda the_driver:the_driver.find_element_by_id('keyword'))
element.send_keys(name)
time.sleep(0.5)
element = WebDriverWait(driver,10).until(lambda the_driver:the_driver.find_element_by_id('btn_query'))
element.click()
time.sleep(0.5)
def get_merge_image(filename,location_list):
im = image.open(filename)
new_im = image.new('RGB', (260,116))
im_list_upper=[]
im_list_down=[]
for location in location_list:
if location['y']==-58:
pass
im_list_upper.append(im.crop((abs(location['x']),58,abs(location['x'])+10,116)))
if location['y']==0:
pass
im_list_down.append(im.crop((abs(location['x']),0,abs(location['x'])+10,58)))
new_im = image.new('RGB', (260,116))
x_offset = 0
for im in im_list_upper:
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
x_offset = 0
for im in im_list_down:
new_im.paste(im, (x_offset,58))
x_offset += im.size[0]
return new_im
def get_image(driver,div):
#找到图片所在的div
background_images=driver.find_elements_by_xpath(div)
location_list=[]
imageurl=''
for background_image in background_images:
# print(re.findall('background-position: (.*)px (.*)px;',background_image.get_attribute('style')))
location={}
# 在html里面解析出小图片的url地址,还有长高的数值
location['x']=int(re.findall('background-position: (.*)px (.*)px;',background_image.get_attribute('style'))[0][0])
location['y']=int(re.findall('background-position: (.*)px (.*)px;',background_image.get_attribute('style'))[0][1])
location_list.append(location)
try:
imageurl=re.findall('url\(\"(.*)\"\)', background_image.get_attribute('style'))[0]
except:
imageurl=re.findall('url\((.*)\)', background_image.get_attribute('style'))[0]
# print(imageurl)
imageurl=imageurl.replace("webp","jpg")
# print(imageurl)
jpgfile=io.BytesIO(urllib.request.urlopen(imageurl).read())
#重新合并图片
image=get_merge_image(jpgfile,location_list )
return image
##比较两张图片的像素点RGB值,相差超过50,即认为是缺口位置
def is_similar(image1,image2,x,y):
pass
pixel1=image1.getpixel((x,y))
pixel2=image2.getpixel((x,y))
for i in range(0,3):
if abs(pixel1[i]-pixel2[i])>=50:
return False
return True
def get_diff_location(image1,image2):
i=0
for i in range(0,260):
for j in range(0,116):
if is_similar(image1,image2,i,j)==False:
return i
##生成鼠标轨迹,待优化
def get_track(length):
//the important alorithmn
def hackgeetest(driver):
#等待图片元素加载出来
WebDriverWait(driver, 10).until(lambda the_driver: the_driver.find_element_by_xpath("//div[@class='gt_slider_knob gt_show']").is_displayed())
WebDriverWait(driver, 10).until(lambda the_driver: the_driver.find_element_by_xpath("//div[@class='gt_cut_bg gt_show']").is_displayed())
WebDriverWait(driver, 10).until(lambda the_driver: the_driver.find_element_by_xpath("//div[@class='gt_cut_fullbg gt_show']").is_displayed())
#下载图片,并重新拼接
image1=get_image(driver,"//div[@class='gt_cut_fullbg_slice']")
# image1.show()
image2=get_image(driver,"//div[@class='gt_cut_bg_slice']")
# image2.show()
#计算缺口位置
loc=get_diff_location(image1,image2)
track_list=get_track(loc)
#找到滑动的圆球
element=driver.find_element_by_xpath("//div[@class='gt_slider_knob gt_show']")
location=element.location
y=location['y']
#鼠标点击元素并按住不放
print ("第一步,点击元素" )
ActionChains(driver).click_and_hold(on_element=element).perform()
time.sleep(0.15)
print("第二步,拖动元素")
for track in track_list:
y=y+random.randint(0,1)
ActionChains(driver).move_to_element_with_offset(to_element=element,xoffset=track[0]+22,yoffset=y).perform()
ActionChains(driver).click_and_hold().perform()
time.sleep(track[1])
print('第三步,释放鼠标')
ActionChains(driver).release(on_element=element).perform()
time.sleep(0.8)
element=WebDriverWait(driver,30).until(lambda the_driver:the_driver.find_element_by_class_name('gt_info_text'))
result = element.text
print(result)
return result
def get_search_list(driver):
#提取条目url,爬取工商信息
#等待搜索结果加载
WebDriverWait(driver, 10).until(lambda the_driver: the_driver.find_element_by_xpath("//div[@class='pagination']"))
# print(driver.page_source)
soup = BeautifulSoup(driver.page_source,'html.parser')
tag=soup.find('div',class_='pagination')
atag=tag.find_all('a')
# pages=int(re.findall('javascript:turnOverPage\((.*)\)',atag[-1].attrs['href'])[0])
# print(pages)
# 打印第一页
print('get_search_item....')
search_list=[]
for sp in soup.find_all('a',attrs={'class':'search_list_item'}):
# print(re.sub('\s+','\n',sp.get_text()))
search_item={}
domain='http://www.gsxt.gov.cn'
search_item['name']=sp.h1.get_text().strip()
li=sp.find_all('span',attrs={'class':'g3'})
search_item['regNo']=li[0].get_text().strip();
search_item['holder']=li[1].get_text().strip();
search_item['foundingTime']=li[2].get_text().strip();
search_item['url']=domain+sp.attrs['href']
search_list.append(search_item)
#访问并打印剩余的页面
# for page in range(pages-1):
# element=WebDriverWait(driver, 30).until(lambda the_driver: the_driver.find_element_by_xpath("//div[@class='pagination']/form/a[last()-1]"))
# element.click()
# soup = BeautifulSoup(driver.page_source,'html.parser')
# for sp in soup.find_all('a',attrs={'class':'search_list_item'}):
# # print(re.sub('\s+','\n',sp.get_text()))
# search_item={}
# search_item['name']=sp.h1.get_text().strip()
# li=sp.find_all('span',attrs={'class':'g3'})
# search_item['regNo']=li[0].get_text().strip();
# search_item['holder']=li[1].get_text().strip();
# search_item['foundingTime']=li[2].get_text().strip();
# search_item['url']=domain+sp.attrs['href']
# search_list.append(search_item)
return search_list
def spiderinfo(searchword,webdriver=1):
#这里的文件路径是webdriver的文件路径
if webdriver==1:
driver = get_webdriver("chrome")
else:
driver = get_webdriver("phantomjs")
input_params(driver,searchword)
#driver.get("localhost:8000/")
flag=True
while flag:
result=hackgeetest(driver)
if '通过' in result:
time.sleep(1)
print('success')
#获取工商企业数据,仅获取第一家
search_list=get_search_list(driver)
# g=getInfo(search_list[0]['url'])
# g.run()
db=DBService()
for item in search_list:
db.insert(1,(item['name'],item['regNo'],item['url'],int(time.time())))
driver.quit()
return search_list
elif '吃' in result:
print('fail')
time.sleep(3)
else:
print("reload")
input_params(driver,searchword)
if __name__=="__main__":
spiderinfo("阿里巴巴")
|
{"/entInfoApi.py": ["/hack.py", "/getInfo.py", "/dbService.py"], "/getInfo.py": ["/dbService.py"]}
|
21,850
|
capme/srcl-2
|
refs/heads/master
|
/tests.py
|
import unittest
import sqlite3
from dua import Cart
class TestCart(unittest.TestCase):
def test_tambahProduk(self):
obj = Cart()
obj.tambahProduk('KODE1', 2)
# now let's check it
conn = sqlite3.connect('example.db')
sql = "SELECT kode_produk, qty FROM cart WHERE kode_produk='KODE1'"
c = conn.cursor()
c.execute(sql)
rows = c.fetchall()
for row in rows:
kode_produk = row[0]
qty = row[1]
self.assertEqual(kode_produk, 'KODE1')
self.assertEqual(qty, 2)
# clean the table
obj.hapusSemuaProduk()
obj.close()
def test_hapusProduk(self):
obj = Cart()
obj.tambahProduk('KODE1', 2)
# now let's check it
conn = sqlite3.connect('example.db')
sql = "SELECT kode_produk, qty FROM cart WHERE kode_produk='KODE1'"
c = conn.cursor()
c.execute(sql)
rows = c.fetchall()
for row in rows:
kode_produk = row[0]
qty = row[1]
self.assertEqual(kode_produk, 'KODE1')
self.assertEqual(qty, 2)
# then hapus produk KODE1
obj.hapusProduk('KODE1')
# check that out
sql = "SELECT COUNT(kode_produk) FROM cart WHERE kode_produk='KODE1'"
c = conn.cursor()
numrows = c.execute(sql).fetchone()[0]
self.assertEqual(numrows, 0)
# clean the table
obj.hapusSemuaProduk()
obj.close()
if __name__ == '__main__':
unittest.main()
|
{"/tests.py": ["/dua.py"]}
|
21,851
|
capme/srcl-2
|
refs/heads/master
|
/dua.py
|
import sqlite3
class Cart:
def __init__(self):
self.conn = sqlite3.connect('example.db')
# create table cart if not exist
sql = "CREATE TABLE IF NOT EXISTS cart (" \
"id INTEGER PRIMARY KEY AUTOINCREMENT, " \
"kode_produk VARCHAR(255) UNIQUE, " \
"qty INT)"
self.c = self.conn.cursor()
self.c.execute(sql)
self.conn.commit()
def tambahProduk(self, kodeProduk, kuantitas):
# sql = "INSERT INTO cart(kode_produk, qty) values (?, ?) ON CONFLICT(kode_produk) DO UPDATE SET qty=qty+?"
sql = "INSERT OR REPLACE INTO cart(kode_produk, qty) VALUES " \
"(?, ?+coalesce((SELECT ifnull(qty, 0) FROM cart WHERE kode_produk=?),0))"
self.c.execute(sql, [kodeProduk, kuantitas, kodeProduk])
self.conn.commit()
def hapusSemuaProduk(self):
sql = "DELETE FROM cart"
self.c.execute(sql)
self.conn.commit()
def hapusProduk(self, kodeProduk):
sql = "DELETE FROM cart WHERE kode_produk='{}'".format(kodeProduk)
self.c.execute(sql)
self.conn.commit()
def tampilkanCart(self):
sql = "SELECT kode_produk, qty FROM cart"
self.c.execute(sql)
rows = self.c.fetchall()
str = ""
for row in rows:
if str == "":
str = "{} ({})".format(row[0], row[1])
else:
str = "\n{} ({})".format(row[0], row[1])
print(str)
def close(self):
self.conn.close()
# obj = Cart()
# obj.tambahProduk('KODE1', 2)
# obj.tampilkanCart()
# obj.close()
# obj.hapusProduk('KODE1')
# obj.tambahProduk('KODE2', 3)
|
{"/tests.py": ["/dua.py"]}
|
21,852
|
drewp/lanscape
|
refs/heads/main
|
/lanscape.py
|
import docopt
from twisted.internet import reactor
import cyclone.httpserver
import cyclone.web
from standardservice.logsetup import log, verboseLogging
from cycloneerr import PrettyErrorHandler
import ingest_ntop
import json
from rdflib import Namespace, Graph, RDFS
MAC = Namespace('http://bigasterisk.com/mac/')
class Report(PrettyErrorHandler, cyclone.web.RequestHandler):
def get(self):
cat_names = {}
g = Graph()
g.parse('netdevices.n3', format='n3')
for s, o in g.subject_objects(RDFS.label):
cat_names[s] = str(o)
byMac = ingest_ntop.ingestNtop()
rows = []
for row in byMac.values():
row['cat_name'] = cat_names.get(MAC[row['mac'].lower()], row['mac'])
rows.append(row)
rows.sort(key=lambda row: row['cat_name'])
json.dump(rows, self)
def main():
args = docopt.docopt('''
Usage:
lanscape.py [options]
Options:
-v, --verbose more logging
''')
verboseLogging(args['--verbose'])
class Application(cyclone.web.Application):
def __init__(self):
handlers = [
(r"/()", cyclone.web.StaticFileHandler, {
'path': '.',
'default_filename': 'index.html'
}),
#(r'/lit/(.*)', cyclone.web.StaticFileHandler, {'path': 'node_modules/lit'}),
(r"/report", Report),
]
cyclone.web.Application.__init__(
self,
handlers,
debug=args['--verbose'],
template_path='.',
)
reactor.listenTCP(8001, Application(), interface='::')
reactor.run()
if __name__ == '__main__':
main()
|
{"/lanscape.py": ["/ingest_ntop.py"]}
|
21,853
|
drewp/lanscape
|
refs/heads/main
|
/ingest_ntop.py
|
import ast
import requests
def ingestNtop():
resp = requests.get('http://10.5.0.1:3000/lua/local/lanscape/main.lua')
byMac = {}
for line in resp.text.splitlines(keepends=False):
if not line.strip():
continue
first, value = line.rsplit(' ', 1)
metric, rest = first.split('{')
labels, _ = rest.split('}')
ld = {}
for label in labels.split(','):
k, v = label.split('=', 1)
ld[k] = ast.literal_eval(v)
if metric == 'hosts_count':
pass
elif metric == 'host_names':
for k, v in ld.items():
byMac.setdefault(ld['mac'], {})[k] = v
else:
byMac.setdefault(ld['mac'], {})[metric] = float(value)
return (byMac)
|
{"/lanscape.py": ["/ingest_ntop.py"]}
|
21,854
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/agri_crawler/daum_blog.py
|
from bs4 import BeautifulSoup
import requests, threading
import time # 시간을 주기 위함
from .models import title ,daum_blog, Emoticon, state1, daum_count # mongodb에 넣기 위함
class daum_crawler(threading.Thread): # 페이지
def __init__(self,keyword, sd,ed,ID,t,b,d,k,tag,comment):
threading.Thread.__init__(self)
self.keyword = keyword
self.sd = sd
self.ed = ed
self.ID = ID
self.t = t
self.b = b
self.d = d
self.k = k
self.tag =tag
self.comment =comment
def get_bs_obj(self, keyword, sd, ed, page): # url 얻고 beautifulsoup 객체 얻을때 사용
url ="https://search.daum.net/search?DA=STC&ed="+ed+"235959"+"&enc=utf8&https_on=on&nil_search=btn&q="+keyword+"&sd="+sd+"000000"+"&w=blog&period=u"+"&page="+page
result = requests.get(url)
bs_obj = BeautifulSoup(result.content, "html.parser")
return bs_obj
def get_bs_incontent(self, url): # 내부 콘텐츠 출력
result = requests.get(url)
bs_obj = BeautifulSoup(result.content, "html.parser")
return bs_obj
def get_data_date(self, keyword, sd, ed,page): # 총 몇 건인지 출력해줌
bs_obj = self.get_bs_obj(keyword, sd, ed,page)
total_num = bs_obj.find("span",{"class":"txt_info"})
total_text = total_num.text
split = total_text.split()
length = len(split)
if length == 4:
text = split[3].replace(",", "")
text = text.replace("건", "")
else:
text = split[2].replace(",", "")
text = text.replace("건", "")
text = int(text)
return text
def run(self):
datevalue = self.get_data_date(self.keyword, self.sd,self.ed,"1")
print(datevalue)
datevalue = int(datevalue/10)
cnt=0
for i in range(1,datevalue):
page = str(i)
bs_obj = self.get_bs_obj(self.keyword, self.sd, self.ed, page)
a_url = bs_obj.findAll("a",{"class":"f_url"})
for i in range(0,len(a_url)):
li = a_url[i]['href']
if "brunch" in li:
time.sleep(2) # 시간 2초로 잡아놓음
bs_obj = self.get_bs_incontent(li)
Title = bs_obj.find("h1",{"class":"cover_title"}).get_text() # 제목
print(Title)
body = bs_obj.find("div",{"class":"wrap_body"}).get_text() # 본문
times = bs_obj.find("span",{"class":"f_l date"}).get_text() # 기간
tags = bs_obj.findAll("ul",{"class":"list_keyword"})
tag_list=""
comment = bs_obj.find("span",{"class":"txt_num"}).text
comment_list=""
if comment == '':
comment=0
else:
comment=int(comment)
print("comment_value:",comment)
if comment >0:
comment_list = comment_collector(li)
for tag in tags:
tag_text = tag.text
print(tag_text)
tag_list +=tag_text
tag_list.rstrip()
daum_Blog = daum_blog()
if self.k != "k":
self.keyword = ""
if self.b != "b":
body = ""
if self.d != "d":
times = ""
if self.t != "t":
Title = ""
if self.tag != "tag":
tag_list= ""
if self.comment !="comment":
comment_list=""
daum_Blog.keyword = self.keyword
daum_Blog.nickname=self.ID
contents = title(main_title = Title,
main_body= body,
datetime=times,media="daum_blog",count=1)
daum_Blog.sub_body = contents
daum_Blog.tag = tag_list
daum_Blog.comment = comment_list
daum_Blog.save()
cnt = cnt+1
print(cnt)
Daum_count = daum_count()
Daum_count.login_id=self.ID
Daum_count.daum_count=cnt
Daum_count.save()
name = state1.objects.filter(login_id = self.ID, type_state=1).order_by('-id').first()
name.state = int(name.state) + cnt
name.save()
def comment_collector(li):
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome('C:/Users/thdwlsgus0/Desktop/chromedriver_win32/chromedriver.exe')
# driver = webdriver.PhantomJS('C:/Users/thdwlsgus0/Desktop/phantomjs-2.1.1-windows/phantomjs-2.1.1-windows/bin/phantomjs.exe')
driver.implicitly_wait(3)
driver.get('https://logins.daum.net/accounts/loginform.do?')
driver.find_element_by_name('id').send_keys('thdwlsgus10')
driver.find_element_by_name('pw').send_keys('operwhe123!')
driver.find_element_by_xpath("//button[@class='btn_comm']").click()
driver.get(li)
html = driver.page_source
soup = BeautifulSoup(html,'html.parser')
notices = soup.findAll("p",{"class":"desc_comment"})
comment_list=""
for comment_div in notices:
value = comment_div.text
print("value: ", value)
comment_list += value
return comment_list
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,855
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/agri_crawler/migrations/0014_remove_state1_total_count.py
|
# Generated by Django 2.1.2 on 2019-02-12 04:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('agri_crawler', '0013_state1_total_count'),
]
operations = [
migrations.RemoveField(
model_name='state1',
name='total_count',
),
]
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,856
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/agri_crawler/migrations/0006_auto_20190131_2200.py
|
# Generated by Django 2.1.2 on 2019-01-31 13:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('agri_crawler', '0005_twitter'),
]
operations = [
migrations.AddField(
model_name='twitter',
name='userId',
field=models.CharField(max_length=200, null=True),
),
migrations.AlterField(
model_name='twitter',
name='Id',
field=models.CharField(max_length=200, null=True),
),
migrations.AlterField(
model_name='twitter',
name='content',
field=models.CharField(max_length=200, null=True),
),
migrations.AlterField(
model_name='twitter',
name='time',
field=models.CharField(max_length=200, null=True),
),
]
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,857
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/agri_crawler/migrations/0016_delete_blog_count.py
|
# Generated by Django 2.1.2 on 2019-02-13 04:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('agri_crawler', '0015_blog_count_news_count_twitter_count'),
]
operations = [
migrations.DeleteModel(
name='blog_count',
),
]
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,858
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/agri_crawler/paginator.py
|
from django.shortcuts import render
from django.core.paginator import Paginator
def page(request):
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,859
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/agri_crawler/migrations/0017_daum_count_naver_count.py
|
# Generated by Django 2.1.2 on 2019-02-13 04:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('agri_crawler', '0016_delete_blog_count'),
]
operations = [
migrations.CreateModel(
name='daum_count',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('login_id', models.CharField(max_length=200, null=True)),
('daum_count', models.CharField(max_length=200, null=True)),
],
),
migrations.CreateModel(
name='naver_count',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('login_id', models.CharField(max_length=200, null=True)),
('naver_count', models.CharField(max_length=200, null=True)),
],
),
]
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,860
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/agri_crawler/forms.py
|
from django import forms
from django.contrib.auth.models import User
from .models import UploadFileModel
from .models import Document
class LoginForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'password']
class UserForm(forms.ModelForm):
class Meta:
model = User
fields =['username', 'password','email']
#def min_length_3_validator(value):
# if len(value) < 3:
# raise forms.ValidationError('3글자 이상 입력해주세요')
class UploadFileForm(forms.ModelForm):
class Meta:
model = UploadFileModel
fields = ('title', 'file')
def __init__(self, *args, **kwargs):
super(PostForm, self).__init__(*args,**kwargs)
self.fields['file'].required = False
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('file', )
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,861
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/agri_crawler/naver_blog.py
|
from bs4 import BeautifulSoup
import requests, threading
import time
from .models import naver,title,state1,naver_count
class naver_crawler(threading.Thread):
def __init__(self, keyword,sd,ed,t,b,d,k,url,ID,number):
threading.Thread.__init__(self)
self.keyword = keyword
self.sd = sd
self.ed = ed
self.t = t
self.b = b
self.d = d
self.k = k
self.url = url
self.ID = ID
self.number = number
def get_data_date(self,keyword, sd, ed, page):
bs_obj = self.get_bs_obj(keyword, sd, ed, page)
total_num = bs_obj.find("span",{"class":"title_num"})
num_split = total_num.text.split()
replace_total = num_split[2].replace(",","")
replace_total = replace_total.replace("건","")
replace_total = int(replace_total)
return replace_total
def get_bs_obj(self, keyword, sd, ed, page):
url="https://search.naver.com/search.naver?where=post&query="+keyword+"&st=sim&sm=tab_opt&date_from="+sd+"&date_to="+ed+"&date_option=8&srchby=all&dup_remove=1&post_blogurl=&post_blogurl_without=&nso=from"+sd+"to"+ed+"&mson=0&start="+page
result = requests.get(url)
bs_obj = BeautifulSoup(result.content, "html.parser")
return bs_obj
def run(self):
datevalue = self.get_data_date(self.keyword, self.sd, self.ed, "1")
datevalue = int(datevalue/10)
print(datevalue)
cnt = 0
for i in range(0,datevalue):
page = str(i*10+1)
time.sleep(2)
bs_obj = self.get_bs_obj(self.keyword, self.sd, self.ed, page)
lis = bs_obj.findAll("li",{"class":"sh_blog_top"})
for li in lis:
Title = li.find("a",{"class":"sh_blog_title"}).text
datetimes = li.find("dd",{"class":"txt_inline"}).text
short_body = li.find("dd",{"class":"sh_blog_passage"}).text
main_url = li.find("a",{"class":"url"})
main_url = main_url['href']
print("ID:",self.ID)
print("title: ", title)
print("datetime: ", datetimes)
print("short_body: ", short_body)
print("main_url: ",main_url)
Naver = naver()
if self.k !="k":
self.keyword=""
if self.b !="b":
short_body=""
if self.d !="d":
datetimes=""
if self.t !="t":
Title =""
if self.url !="url":
main_url =""
Naver.keyword = self.keyword
Naver.nickname= self.ID
contents = title(main_title=Title,
main_body=short_body,
datetime=datetimes,
media="naver_blog",
count="1")
Naver.sub_body = contents
Naver.main_url=main_url
Naver.save()
cnt = cnt+1
print(cnt)
Naver = naver_count()
Naver.login_id=self.ID
Naver.naver_count=cnt
Naver.save()
name = state1.objects.filter(id=self.number, type_state=1).order_by('-id').first()
name.state= int(name.state) + cnt
name.save()
print("끝")
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,862
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/example_python/language.py
|
# twitter를 사용해야할 것 같음.
from konlpy.tag import Twitter
file = open("output.txt","r",encoding="utf-8")
twitter = Twitter()
word_dic = {}
line = file.read()
lines = line.split("\r\n") #한줄한줄 분할
for line in lines:
malist = twitter.pos(line)
print(malist)
for taeso,pumsa in malist:
if pumsa == "Noun":
if not (taeso in word_dic):
word_dic[taeso]=0
word_dic[taeso]+=1
keys = sorted(word_dic.items(), key=lambda x:x[1], reverse=True)
for word, count in keys[:50]:
print("{0}({1}) ".format(word, count), end="")
print(word_dic)
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,863
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/agri_crawler/migrations/0013_state1_total_count.py
|
# Generated by Django 2.1.2 on 2019-02-12 04:45
import agri_crawler.models
from django.db import migrations
import djongo.models.fields
class Migration(migrations.Migration):
dependencies = [
('agri_crawler', '0012_auto_20190203_1930'),
]
operations = [
migrations.AddField(
model_name='state1',
name='total_count',
field=djongo.models.fields.EmbeddedModelField(model_container=agri_crawler.models.media_count, model_form_class=agri_crawler.models.media_countForm, null=True),
),
]
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,864
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/agri_crawler/migrations/0001_initial.py
|
# Generated by Django 2.1.3 on 2019-01-07 11:31
import agri_crawler.models
from django.db import migrations, models
import djongo.models.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='dailyEconomy',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('keyword', models.CharField(max_length=130)),
('sub_body', djongo.models.fields.EmbeddedModelField(model_container=agri_crawler.models.title, model_form_class=agri_crawler.models.titleForm, null=True)),
],
),
migrations.CreateModel(
name='daum',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('keyword', models.CharField(max_length=130)),
('sub_body', djongo.models.fields.EmbeddedModelField(model_container=agri_crawler.models.title, model_form_class=agri_crawler.models.titleForm, null=True)),
],
),
migrations.CreateModel(
name='daum_blog',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('keyword', models.CharField(max_length=100)),
('sub_body', djongo.models.fields.EmbeddedModelField(model_container=agri_crawler.models.title, model_form_class=agri_crawler.models.titleForm, null=True)),
],
),
migrations.CreateModel(
name='Document',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.CharField(blank=True, max_length=255)),
('file', models.FileField(upload_to='webapp/')),
('uploaded_at', models.DateTimeField(auto_now_add=True)),
],
),
migrations.CreateModel(
name='eDaily',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('keyword', models.CharField(max_length=130)),
('sub_body', djongo.models.fields.EmbeddedModelField(model_container=agri_crawler.models.title, model_form_class=agri_crawler.models.titleForm, null=True)),
],
),
migrations.CreateModel(
name='JTBC',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('keyword', models.CharField(max_length=130)),
('sub_body', djongo.models.fields.EmbeddedModelField(model_container=agri_crawler.models.title, model_form_class=agri_crawler.models.titleForm, null=True)),
],
),
migrations.CreateModel(
name='KBS',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('keyword', models.CharField(max_length=100)),
('sub_body', djongo.models.fields.EmbeddedModelField(model_container=agri_crawler.models.title, model_form_class=agri_crawler.models.titleForm, null=True)),
],
),
migrations.CreateModel(
name='koreaEconomy',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('keyword', models.CharField(max_length=130)),
('sub_body', djongo.models.fields.EmbeddedModelField(model_container=agri_crawler.models.title, model_form_class=agri_crawler.models.titleForm, null=True)),
],
),
migrations.CreateModel(
name='MBC',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('keyword', models.CharField(max_length=200)),
('sub_body', djongo.models.fields.EmbeddedModelField(model_container=agri_crawler.models.title, model_form_class=agri_crawler.models.titleForm, null=True)),
],
),
migrations.CreateModel(
name='moneyToday',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('keyword', models.CharField(max_length=130)),
('sub_body', djongo.models.fields.EmbeddedModelField(model_container=agri_crawler.models.title, model_form_class=agri_crawler.models.titleForm, null=True)),
],
),
migrations.CreateModel(
name='naver',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('keyword', models.CharField(max_length=130)),
('sub_body', djongo.models.fields.EmbeddedModelField(model_container=agri_crawler.models.title, model_form_class=agri_crawler.models.titleForm, null=True)),
],
),
migrations.CreateModel(
name='SBS',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('keyword', models.CharField(max_length=100)),
('sub_body', djongo.models.fields.EmbeddedModelField(model_container=agri_crawler.models.title, model_form_class=agri_crawler.models.titleForm, null=True)),
],
),
migrations.CreateModel(
name='seoulEconomy',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('keyword', models.CharField(max_length=130)),
('sub_body', djongo.models.fields.EmbeddedModelField(model_container=agri_crawler.models.title, model_form_class=agri_crawler.models.titleForm, null=True)),
],
),
migrations.CreateModel(
name='Signup',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ID', models.CharField(max_length=100)),
('password', models.CharField(max_length=100)),
('Email', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='state1',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('login_id', models.CharField(max_length=100)),
('keyword', models.CharField(max_length=100)),
('start_date', models.CharField(max_length=100)),
('end_date', models.CharField(max_length=100)),
('today_date', models.CharField(max_length=100)),
('state', models.CharField(max_length=100, null=True)),
('type_state', models.CharField(max_length=100, null=True)),
],
),
migrations.CreateModel(
name='UploadFileModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.TextField(default='')),
('file', models.FileField(null=True, upload_to='')),
],
),
migrations.CreateModel(
name='user_data',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ID', models.CharField(max_length=100)),
('keyword', models.CharField(max_length=100)),
('sub_body', djongo.models.fields.EmbeddedModelField(model_container=agri_crawler.models.title, model_form_class=agri_crawler.models.titleForm, null=True)),
],
),
migrations.CreateModel(
name='YTN',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('keyword', models.CharField(max_length=130)),
('sub_body', djongo.models.fields.EmbeddedModelField(model_container=agri_crawler.models.title, model_form_class=agri_crawler.models.titleForm, null=True)),
],
),
]
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,865
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/example_python/practice_layer.py
|
from practice_bayes import Bayes
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,866
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/agri_crawler/RNN_model.py
|
import matplotlib.pyplot as plt
from . import GL_ModelCreator as gmc
from . import GL_DataLoader as gdl
import numpy as np
import csv
class Analysis:
def __init__(self, x_axis, y_axis):
data_loader = gdl.GLDataLoader(x_axis, y_axis)
nptf =data_loader.normalizing()
data_loader.spliter(nptf)
scaler = data_loader.scaler
model = gmc.ModelsCreator()
model.settingLearningEnvironment()
last_x = nptf[-1]
last_x = np.reshape(last_x, (1, 1, 1))
hist = model.training(data_loader.for_train_x, data_loader.for_train_y, data_loader.for_test_x, data_loader.for_test_y)
test_predict, test_y = model.tester(data_loader.for_test_x, data_loader.for_test_y, nptf, scaler)
plt.plot(test_predict, "g-")
plt.plot(test_y, "r-")
plt.show()
plt.close()
fig, loss_ax = plt.subplots()
acc_ax = loss_ax.twinx()
loss_ax.plot(hist.history['loss'], 'y', label='train loss')
loss_ax.plot(hist.history['val_loss'], 'r', label='val loss')
loss_ax.set_xlabel('epoch')
loss_ax.set_ylabel('loss')
loss_ax.legend(loc='upper left')
plt.show()
extest=np.array([1.6,1.2,1.2,1.3,1.2,1,0.4,-0.1,0.6,1.5,2.3,3,4.4,4.3,3.6])
look_back = 15
day=30
log=[]
for step in range(day):
extest2 = np.reshape(extest, [-1, 1])
extest2 = scaler.fit_transform(extest2)
extest2 = extest2.reshape([1, 1, look_back])
temp=scaler.inverse_transform(model.model.predict(extest2))
print("day",step+1,":",temp)
log.append(temp[0][0])
for i in range(len(extest)-1):
extest[i]=extest[i+1]
extest[look_back-1]=temp
plt.plot(log)
plt.show()
f = open('output.csv', 'w', encoding='utf-8', newline='')
wr = csv.writer(f)
wr.writerow(['Date , late'])
np.reshape(test_predict, [-1])
print(np.shape(test_predict))
for i in range(test_predict.size):
wr.writerow([data_loader.date[i], test_predict[i, 0]])
f.close()
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,867
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/agri_crawler/migrations/0007_auto_20190201_1615.py
|
# Generated by Django 2.1.2 on 2019-02-01 07:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('agri_crawler', '0006_auto_20190131_2200'),
]
operations = [
migrations.AddField(
model_name='daum_blog',
name='nickname',
field=models.CharField(max_length=100, null=True),
),
migrations.AlterField(
model_name='daum_blog',
name='keyword',
field=models.CharField(max_length=100, null=True),
),
migrations.AlterField(
model_name='naver',
name='keyword',
field=models.CharField(max_length=130, null=True),
),
]
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,868
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/agri_crawler/twitter.py
|
from bs4 import BeautifulSoup
import requests
def get_url(url):
result = requests.get(url)
soup = BeautifulSoup(result.content, "html.parser")
return soup
url = "https://search.daum.net/search?w=social&m=web&sort_type=socialweb&nil_search=btn&DA=NTB&enc=utf8&q=감자"
soup = get_url(url)
div_list = soup.findAll("div",{"class":"box_con"})
for list in div_list:
title = list.find("div",{"class":"wrap_tit"}).text
print(title)
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,869
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/agri_crawler/migrations/0004_daum_blog_comment.py
|
# Generated by Django 2.1.3 on 2019-01-09 11:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('agri_crawler', '0003_daum_blog_tag'),
]
operations = [
migrations.AddField(
model_name='daum_blog',
name='comment',
field=models.CharField(max_length=10000, null=True),
),
]
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,870
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/agri_crawler/migrations/0010_auto_20190201_1650.py
|
# Generated by Django 2.1.2 on 2019-02-01 07:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('agri_crawler', '0009_auto_20190201_1648'),
]
operations = [
migrations.AddField(
model_name='dailyeconomy',
name='nickname',
field=models.CharField(max_length=130, null=True),
),
migrations.AddField(
model_name='edaily',
name='nickname',
field=models.CharField(max_length=130, null=True),
),
migrations.AddField(
model_name='jtbc',
name='nickname',
field=models.CharField(max_length=130, null=True),
),
migrations.AddField(
model_name='kbs',
name='nickname',
field=models.CharField(max_length=130, null=True),
),
migrations.AddField(
model_name='mbc',
name='nickname',
field=models.CharField(max_length=130, null=True),
),
migrations.AddField(
model_name='moneytoday',
name='nickname',
field=models.CharField(max_length=130, null=True),
),
migrations.AddField(
model_name='sbs',
name='nickname',
field=models.CharField(max_length=130, null=True),
),
migrations.AddField(
model_name='seouleconomy',
name='nickname',
field=models.CharField(max_length=130, null=True),
),
migrations.AddField(
model_name='ytn',
name='nickname',
field=models.CharField(max_length=130, null=True),
),
migrations.AlterField(
model_name='dailyeconomy',
name='keyword',
field=models.CharField(max_length=130, null=True),
),
migrations.AlterField(
model_name='edaily',
name='keyword',
field=models.CharField(max_length=130, null=True),
),
migrations.AlterField(
model_name='jtbc',
name='keyword',
field=models.CharField(max_length=130, null=True),
),
migrations.AlterField(
model_name='kbs',
name='keyword',
field=models.CharField(max_length=130, null=True),
),
migrations.AlterField(
model_name='mbc',
name='keyword',
field=models.CharField(max_length=130, null=True),
),
migrations.AlterField(
model_name='moneytoday',
name='keyword',
field=models.CharField(max_length=130, null=True),
),
migrations.AlterField(
model_name='sbs',
name='keyword',
field=models.CharField(max_length=130, null=True),
),
migrations.AlterField(
model_name='seouleconomy',
name='keyword',
field=models.CharField(max_length=130, null=True),
),
migrations.AlterField(
model_name='ytn',
name='keyword',
field=models.CharField(max_length=130, null=True),
),
]
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,871
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/example_python/base_layer.py
|
rom bayes import BayesianFilter
from practice_bayes import Bayes
bf = BayesianFilter()
# 텍스트 학습
bf.fit("쿠폰 선물 & 무료 배송", "광고")
print(bf.category_dict)
print(bf.word_dict)
print(bf.words)
print("-=-=-=-=-=-=-=-=-=-=")
# 예측
pre, scorelist = bf.predict("재고 정리 할인, 무료 배송")
print("결과 = ", pre)
print(scorelist)
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
21,872
|
thdwlsgus0/vegetable_crawler
|
refs/heads/master
|
/agriculture/agriculture/agri_crawler/classfier.py
|
"""from konlpy.tag import *
from konlpy.utils import pprint
from konlpy.tag import Okt
class classfier():
def __init__(self):
self.positive = 0
self.negative = 0
self.list_positive = []
self.list_negetive = []
self.list_neutral = []
def getting_list(self, filename, listname):
okt = Okt()
while 1:
line = filename.readline()
Str = str(line)
line_parse = okt.morphs(Str)
for i in line_parse:
listname.append(i)
if not line:
break
return listname
def naive_bayes_classifier(self,test, train, all_count):
counter = 0
list_count = []
for i in test:
for j in range(len(train)):
if i == train[j]:
counter = counter + 1
list_count.append(counter)
counter = 0
list_naive = []
for i in range(len(list_count)):
list_naive.append((list_count[i]+1)/float(len(train)+all_count))
result = 1
for i in range(len(list_naive)):
result *= float(round(list_naive[i], 6))
return float(result)*float(1.0/3.0)
def naive_classfier(self, text_line):
f_pos = open('positive1.txt','r')
f_neg = open('negetive.txt','r')
f_neu = open('neutral.txt','r')
okt = Okt()
input_kkma = okt.morphs(str(text_line)) # 형태소 별로 토큰화
test_output = []
for i in input_kkma:
test_output.append(i)
list_pos = self.getting_list(f_pos,self.list_positive)
list_neg = self.getting_list(f_neg,self.list_negetive)
list_neu = self.getting_list(f_neu,self.list_neutral)
ALL = len(list_pos)+len(list_neg)+len(list_neu)
result_pos = self.naive_bayes_classifier(test_output, list_pos, ALL)
result_neg = self.naive_bayes_classifier(test_output, list_neg, ALL)
result_neu = self.naive_bayes_classifier(test_output, list_neu, ALL)
if result_pos>result_neg and result_pos>result_neu:
return 1
elif result_pos<result_neg and result_neu<result_neg:
return 0
else:
return -1 """
|
{"/agriculture/agriculture/agri_crawler/daum_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/forms.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/naver_blog.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/blogview.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/views.py": ["/agriculture/agriculture/agri_crawler/models.py", "/agriculture/agriculture/agri_crawler/forms.py", "/agriculture/agriculture/agri_crawler/signup.py", "/agriculture/agriculture/agri_crawler/blogview.py", "/agriculture/agriculture/agri_crawler/daum_blog.py", "/agriculture/agriculture/agri_crawler/naver_blog.py", "/agriculture/agriculture/agri_crawler/news.py", "/agriculture/agriculture/agri_crawler/Analysis.py"], "/agriculture/agriculture/agri_crawler/news.py": ["/agriculture/agriculture/agri_crawler/models.py"], "/agriculture/agriculture/agri_crawler/signup.py": ["/agriculture/agriculture/agri_crawler/models.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.