Commit 39771d1f by 赵宇

fix

parent 66d4302a
......@@ -87,13 +87,13 @@ def creat_app(config_name):
app.url_map.converters['re'] = RegexConverter
# 注册蓝图,推迟导入,防止循环嵌套
from apps.view_attract import api_attract # 招商驾驶舱
from apps.index import api_attract # 招商驾驶舱
# from apps.user_pc import api_user
from apps.atlas import api_atlas
from apps.radar import api_radar
from apps.attract import api_map
from apps.attract_map import api_map
# from apps.view_360 import api_portraits
# from apps.view_choose_address import api_address
from apps.choose_address import api_address
# from apps.manage import api_power
# from apps.inves_manage import api_manage
# from apps.view_mobile import api_mobile
......@@ -103,9 +103,9 @@ def creat_app(config_name):
app.register_blueprint(api_atlas, url_prefix='/api/atlas') # 产业招商图谱
app.register_blueprint(api_map, url_prefix='/api/map') # 产业招商地图
app.register_blueprint(api_attract, url_prefix='/api/attract/industry') # 招商驾驶舱
app.register_blueprint(api_attract, url_prefix='/api/attract_map/industry') # 招商驾驶舱
# app.register_blueprint(api_portraits, url_prefix="/api/portraits/industry")
# app.register_blueprint(api_address, url_prefix="/api/address/industry")
app.register_blueprint(api_address, url_prefix="/api/address")
# app.register_blueprint(api_power, url_prefix="/api/power")
# app.register_blueprint(api_manage, url_prefix="/api/manage")
# app.register_blueprint(api_mobile, url_prefix="/api/mobile")
......
# from flask import current_app, request, jsonify
# from apps.atlas import api_atlas
# from sqlalchemy import extract, or_, and_
# from sqlalchemy.sql import func
# from apps.models import *
# from apps.util import login_required, verify_token
# from apps.utils.response_code import RET
# from datetime import datetime, timedelta
#
#
# # 行业分类自定义层级信息全部获取(2020-11-3)
# @api_atlas.route('/get_fields', methods=['GET'])
from flask import current_app, request, jsonify
from apps.atlas import api_atlas
from apps.util import login_required
from apps.utils.response_code import RET
from apps.models import *
from apps.utils.neo4j_conn import conn_neo4j, neo4j_dict
from apps import redis_store
import json
graph = conn_neo4j()
'''行业名转换ptp字典两个 neo4j_dict line 164/177'''
def deleteDuplicate(li):
'''列表[字典]去重'''
temp_list = list(set([str(i) for i in li]))
li = [eval(i) for i in temp_list]
return li
def find_up_thr(name_query, relation):
if relation == "中游行业":
relation_c = "下位产品"
else:
relation_c = relation
# 零级,上中下三游
data = {
"node": "{}".format(relation[:2]),
"level": 1,
"subNodeList": [],
}
sql_01 = "match (n) -[r:`{}`]->(m) WHERE n.name='{}' return n.name,r.type,m.name".format(relation_c, name_query)
res_zero = graph.run(sql_01).data()
res_one = list(set([i["m.name"] for i in list(res_zero)])) # 不重复的一级节点
for it in res_one: # 一级节点
pname_one = it
# 一级
node_one = {
"node": "{}".format(pname_one),
"level": 2,
"subNodeList": []
}
sql_02 = "match (n) -[r]->(m) WHERE n.name='{}' return n.name,r.type,m.name".format(pname_one)
result = graph.run(sql_02).data()
result = list(set([i["m.name"] for i in list(result)])) # 不重复的二级节点
for item in result:
pname_two = item
# 二级
node_two = {
"node": "{}".format(pname_two),
"level": 3,
"subNodeList": []
}
sql_03 = "match (n) -[r]->(m) WHERE n.name='{}' return n.name,r.type,m.name".format(pname_two)
result3 = graph.run(sql_03).data()
result3 = list(set([i["m.name"] for i in list(result3)])) # 不重复的三级节点
for itm in result3:
pname_thr = itm
# 三级
node_thr = {
"node": "{}".format(pname_thr),
"level": 4,
"subNodeList": []
}
node_two["subNodeList"].append(node_thr)
node_one["subNodeList"].append(node_two)
data["subNodeList"].append(node_one)
return data
# 获取产业集群名称
@api_atlas.route('/industry/cluster', methods=['GET'])
def get_cluster():
try:
cluster_obj = Industry.query.filter_by(fid=0).all()
data = {
"cluster": [
{"id": i.nid, 'industry_level': 1, 'name': i.name,
"subNodeList": [{'id': j.nid, 'industry_level': 2, "name": j.name} for j in
Industry.query.filter_by(fid=i.nid)]} for i in
cluster_obj]
}
return jsonify(code=RET.OK, msg='产业集群名称获取成功!', data=data)
except Exception as e:
current_app.logger.error(e)
# 行业产品公司数量(链图,根据地理位置)
@api_atlas.route('/industry/chain', methods=['POST'])
# @login_required
# def get_fields():
# '''获取左侧导航信息一览,两级导航'''
# try:
# # 获取一级行业
# fields = Industry.query.filter_by(fid=0, statu=1).all()
# print(fields)
# data = []
# for field in fields:
# df = {"id": field.nid,
# "cate": "1",
# "label": field.name,
# "children": []}
# childs = Industry.query.filter_by(fid=field.nid, statu=1).all()
# for child in childs:
# df["children"].append({"id": child.nid,
# "label": child.name,
# "cate": "2"})
# data.append(df)
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DBERR, msg="数据异常")
# return jsonify(code=RET.OK, msg="获取成功", navleftdata=data)
#
#
# # 二级行业收藏状态获取
# @api_atlas.route('/inducollect/<id>', methods=['GET'])
def industry_chain():
'''
行业id->行业链标题-》上中下游-》查询数值
:return:
'''
req_dict = request.get_json()
inid = req_dict.get("inid") # 二级行业id(二级行业显示链图)
# district = req_dict.get("district") # 区县
# 校验参数完整性
if not all([inid]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
try:
# name_query = "jc" + str(inid) + str(district)
# if redis_store.get(name_query) is not None:
# data = json.loads(redis_store.get(name_query))
# return jsonify(code=RET.OK, msg="获取成功", data=data)
# 行业使用名
industryName = Industry.query.filter_by(nid=inid).first().oname
ptp = neo4j_dict()
if industryName in ptp:
industryName = ptp[industryName]
# print(industryName)
result = {
"industryChain": industryName,
"nodeList": [find_up_thr(industryName, "上游行业"),
find_up_thr(industryName, "中游行业"),
find_up_thr(industryName, "下游行业")]
}
# redis缓存
# redis_store.set(name_query, json.dumps(result))
# redis_store.expire(name_query, 30 * 24 * 3600)
# print("redis")
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据异常")
return jsonify(code=RET.OK, msg="获取成功", data=result)
# 点击产业联动显示企业
@api_atlas.route('/industry/enterprise', methods=['POST'])
# @login_required
# def inducollect(id):
# '''获取当前用户对二级行业的收藏状态'''
# token = request.headers["token"]
# user = verify_token(token)
# user_id = user.id # 用户id
# try:
# user = User.query.get(user_id) # 获取关注列表
# industrys = user.industry
# if industrys:
# indu_ids = [indu.id for indu in user.industry]
# else:
# indu_ids = []
# if int(id) in indu_ids:
# return jsonify(code=RET.OK, msg="查询成功", collect="1")
# else:
# return jsonify(code=RET.OK, msg="查询成功", collect="2")
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DBERR, msg="数据库查询错误")
#
#
# # 行业业收藏与取消
# @api_atlas.route('/industry/collect', methods=['POST'])
# @login_required
# def indu_collect():
# '''企业收藏与状态取消'''
# token = request.headers["token"]
# user = verify_token(token)
# user_id = user.id # 用户id
#
# req_dict = request.get_json()
# _id = req_dict.get("id") # 二级行业id
# collect = req_dict.get("collect") # 关注状态(1是,2否)
# # 校验参数完整性
# if not all([_id, collect]):
# return jsonify(code=RET.PARAMERR, msg="参数不完整")
# try:
# if collect == "2": # 未关注,我要关注
# user = User.query.get(user_id)
# indu = Industry.query.filter_by(nid=_id).first()
# user.industry.append(indu)
# db.session.commit()
# return jsonify(code=RET.OK, msg="收藏成功", collect="1")
# elif collect == "1": # 已关注,我要取关
# user = User.query.get(user_id)
# indu = Industry.query.filter_by(nid=_id).first()
# user.industry.remove(indu)
# db.session.commit()
# return jsonify(code=RET.OK, msg="取消收藏", collect="2")
# else:
# return jsonify(code=RET.DATAERR, msg="参数异常")
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DBERR, msg="数据库查询错误")
#
#
# # 太原市企业条件选择导航(类型,资质,上市,融资,时间,注册资本,区县选择)
# @api_atlas.route('/industry/field', methods=['GET'])
# # @login_required
# def field():
# '''太原市企业条件选择导航获取'''
# try:
# property = Propertyty.query.filter_by(statu=1)
# typy = property.filter_by(sid=1, statu=1).all()
# qualificat = property.filter_by(sid=2, statu=1).all()
# quoted = property.filter_by(sid=3, statu=1).all()
# financ = property.filter_by(sid=4, statu=1).all()
# # options: [{ value: "选项1", label: "无数据" },{ value: "选项2", label: "3333" }],
# data = {"entype": [{"label": i.name, "value": i.nid} for i in typy],
# "qualificat": [{"label": i.name, "value": i.nid} for i in qualificat],
# "quoted": [{"label": i.name, "value": i.nid} for i in quoted],
# "financ": [{"label": i.name, "value": i.nid} for i in financ],
# "buildate": [{"label": "1-3年", "value": 1}, {"label": "3-5年", "value": 2},
# {"label": "5-8年", "value": 3}, {"label": "8-10年", "value": 4},
# {"label": "10-15年", "value": 5}, {"label": "15年以上", "value": 6}],
# "capital": [{"label": "100万以内", "value": 1}, {"label": "100万-500万", "value": 2},
# {"label": "500万-1000万", "value": 3}, {"label": "1000万-5000万", "value": 4},
# {"label": "5000万-1亿", "value": 5}, {"label": "1亿以上", "value": 6}],
# "district": [{"label": "小店区", "value": "小店区"}, {"label": "迎泽区", "value": "迎泽区"},
# {"label": "杏花岭区", "value": "杏花岭区"}, {"label": "尖草坪区", "value": "尖草坪区"},
# {"label": "万柏林区", "value": "万柏林区"}, {"label": "晋源区", "value": "晋源区"},
# {"label": "清徐县", "value": "清徐县"}, {"label": "阳曲县", "value": "阳曲县"},
# {"label": "娄烦县", "value": "娄烦县"}, {"label": "古交市", "value": "古交市"}],
# # "district": [{"label": "小店区", "value": ""}, {"label": "迎泽区", "value": 2},
# # {"label": "杏花岭区", "value": 3}, {"label": "尖草坪区", "value": 4},
# # {"label": "万柏林区", "value": 5}, {"label": "晋源区", "value": 6},
# # {"label": "清徐县", "value": 7}, {"label": "阳曲县", "value": 8},
# # {"label": "娄烦县", "value": 9}, {"label": "古交市", "value": 10}]
# }
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DBERR, msg="数据库查询错误")
# return jsonify(code=RET.OK, msg="获取成功", options=data)
#
#
# # 行业信息总览
# @api_atlas.route('/industry/overview', methods=['POST'])
# # @login_required
# def overview():
# '''太原市行业信息总览'''
# req_dict = request.get_json()
# inid = req_dict.get("inid") # 行业id
# cate = req_dict.get("cate") # 行业等级,(高端设备等五个为"1",子行业为"2")
#
# entype = req_dict.get("entype") # 企业类型id
# qualificat = req_dict.get("qualificat") # 企业资质id
# capital = req_dict.get("capital") # 注册资本id
# quoted = req_dict.get("quoted") # 上市板块
# district = req_dict.get("district") # 太原市下区县
# yearid = req_dict.get("yearid") # 成立时间年限id
# roundid = req_dict.get("roundid") # 融资轮次id(天使/种子,1)(PreA/A+,2)(PreB/B+,3)(C轮以上,4)(收并购,5)(战略投资,6)(其他,7)
# product = req_dict.get("product") # 产业产品选择
#
# # 校验参数完整性
# if not all([inid, cate]):
# return jsonify(code=RET.PARAMERR, msg="参数不完整")
#
# try:
# if cate == "1":
# company = Company.query.filter_by(f_type=inid, city="太原市")
# else:
# company = Company.query.filter_by(c_type=inid, city="太原市")
# # 企业类型
# if entype:
# company = company.filter_by(entypeid=entype)
# # 企业资质
# if qualificat:
# if qualificat == 1:
# company = company.filter_by(high_new=1)
# if qualificat == 2:
# company = company.filter_by(tbe=1)
# if qualificat == 3:
# company = company.filter_by(quoted_company=1)
# if qualificat == 4:
# company = company.filter_by(sxonhun=1)
# if qualificat == 5:
# company = company.filter_by(isfive=1)
# if qualificat == 6:
# company = company.filter_by(unicorn=1)
# if qualificat == 7:
# company = company.filter_by(dengl=1)
# if qualificat == 8:
# company = company.filter_by(zjtg=1)
# if qualificat == 9:
# company = company.filter_by(scale=1)
# if qualificat == 10:
# company = company.filter_by(serve=1)
# # 注册资本
# if capital:
# company = company.filter_by(capital_id=capital)
# # 上市板块
# if quoted:
# company = company.filter_by(public_id=quoted)
# # 区域选择
# if district:
# company = company.filter_by(district=district)
# # 成立时间id
# if yearid:
# company = company.filter_by(yearid=yearid)
# # 融资轮次
# if roundid:
# company = company.filter_by(roundid=roundid)
# if product:
# company = Company.query.filter(Company.product_all.like("%{}%".format(product)))
# coms = company.count() # 企业总数
# capital = round(float(company.with_entities(func.sum(Company.capital_nums)).scalar() if company.with_entities(
# func.sum(Company.capital_nums)).scalar() else 0) / 10000, 2) # 注册资本单位万
# taking = round(float(company.with_entities(func.sum(Company.takingn)).scalar() if company.with_entities(
# func.sum(Company.takingn)).scalar() else 0) / 10000, 2) # 营收
# profit = round(float(company.with_entities(func.sum(Company.profit)).scalar() if company.with_entities(
# func.sum(Company.profit)).scalar() else 0) / 10000, 2) # 利润
# # profit = "0" # 利润
# pnums = round(float(company.with_entities(func.sum(Company.bao_num)).scalar() if company.with_entities(
# func.sum(Company.bao_num)).scalar() else 0)) # 参保人数
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DBERR, msg="数据库查询错误")
#
# data = {"coms": str(coms) + "户", "capital": str(capital) + "亿", "taking": str(taking) + "亿",
# "pnums": str(pnums) + "人", "profit": str(profit) + "亿"}
#
# return jsonify(code=RET.OK, msg="获取成功", data=data)
#
#
# # 太原市企业年度柱状图
# @api_atlas.route('/industry/statistics', methods=['POST'])
# # @login_required
# def statistics():
# '''太原市企业年度柱状图'''
# req_dict = request.get_json()
# inid = req_dict.get("inid") # 行业id
# cate = req_dict.get("cate") # 行业等级,(高端设备等五个为"1",子行业为"2")
#
# entype = req_dict.get("entype") # 企业类型id
# qualificat = req_dict.get("qualificat") # 企业资质id
# capital = req_dict.get("capital") # 注册资本id
# quoted = req_dict.get("quoted") # 上市板块
# district = req_dict.get("district") # 太原市下区县
# yearid = req_dict.get("yearid") # 成立时间年限id
# roundid = req_dict.get("roundid") # 融资轮次id(天使/种子,1)(PreA/A+,2)(PreB/B+,3)(C轮以上,4)(收并购,5)(战略投资,6)(其他,7)
# product = req_dict.get("product") # 产业产品选择
#
# # 校验参数完整性
# if not all([inid, cate]):
# return jsonify(code=RET.PARAMERR, msg="参数不完整")
#
# try:
# if cate == "1":
# company = Company.query.filter_by(f_type=inid, city="太原市")
# else:
# company = Company.query.filter_by(c_type=inid, city="太原市")
# # 企业类型
# if entype:
# company = company.filter_by(entypeid=entype)
# # 企业资质
# if qualificat:
# if qualificat == 1:
# company = company.filter_by(high_new=1)
# if qualificat == 2:
# company = company.filter_by(tbe=1)
# if qualificat == 3:
# company = company.filter_by(public_sector=1)
# if qualificat == 4:
# company = company.filter_by(sxonhun=1)
# if qualificat == 5:
# company = company.filter_by(isfive=1)
# if qualificat == 6:
# company = company.filter_by(unicorn=1)
# if qualificat == 7:
# company = company.filter_by(dengl=1)
# if qualificat == 8:
# company = company.filter_by(zjtg=1)
# if qualificat == 9:
# company = company.filter_by(scale=1)
# if qualificat == 10:
# company = company.filter_by(serve=1)
# # 注册资本
# if capital:
# company = company.filter_by(capital_id=capital)
# # 上市板块
# if quoted:
# company = company.filter_by(public_id=quoted)
# # 区域选择
# if district:
# company = company.filter_by(district=district)
# # 成立时间id
# if yearid:
# company = company.filter_by(yearid=yearid)
# # 融资轮次
# if roundid:
# company = company.filter_by(roundid=roundid)
# if product:
# company = company.filter(Company.product_all.like("%{}%".format(product)))
# yearn = datetime.now().year
# data = {"register": [], "cpital": []}
# for year in [str(y) for y in range(yearn - 4, yearn + 1)]:
# data["register"].append(
# {"year": year, "value": company.filter(extract("year", Company.build_date) == year).count()})
# v = company.filter(extract("year", Company.build_date) == year).with_entities(
# func.sum(Company.capital_nums)).scalar()
# data["cpital"].append({"year": year, "value": round(float(v), 2) if v else 0})
#
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DBERR, msg="数据库查询错误")
#
# return jsonify(code=RET.OK, msg="获取成功", data=data)
#
#
# # 太原市创新资源机构类型筛选条件
# @api_atlas.route('/innovate/fields', methods=['GET'])
# def org_field():
# '''创新资源机构列表'''
# # data = {"class": [{"label": "高等院校", "value": 1}, {"label": "科研机构", "value": 2},
# # {"label": "创新平台", "value": 3}, {"label": "产业服务平台", "value": 4}],
# # "college": [{"label": "全部", "value": ""}, {"label": "211工程院校", "value": 1},
# # {"label": "普通本科", "value": 2}, {"label": "高职高专", "value": 3}],
# # "scenice": [],
# # "creative": [{"label": "全部", "value": ""}, {"label": "工程技术中心", "value": 1},
# # {"label": "国际科技合作基地", "value": 2},
# # {"label": "企业技术中心", "value": 3}, {"label": "双创基地", "value": 4},
# # {"label": "院士工作站", "value": 5}, {"label": "质量检测与测量中心", "value": 6},
# # {"label": "重点实验室", "value": 7}],
# # "induserve": [{"label": "全部", "value": ""}, {"label": "产业联盟", "value": 1},
# # {"label": "公共服务平台", "value": 2}, {"label": "行业协会", "value": 3}]
# # }
#
# data = {"class": [{"label": "高等院校", "value": 1}, {"label": "科研机构", "value": 2},
# {"label": "创新平台", "value": 3}, {"label": "产业服务平台", "value": 4}],
# "college": [{"label": "全部", "value": ""}, {"label": "211工程院校", "value": 1},
# {"label": "普通本科", "value": 2}, {"label": "高职高专", "value": 3}],
# "scenice": [],
# "creative": [{"label": "全部", "value": ""}, {"label": "工程技术中心", "value": 1},
# {"label": "国际科技合作基地", "value": 2},
# {"label": "企业技术中心", "value": 3}, {"label": "双创基地", "value": 4},
# {"label": "重点实验室", "value": 7}],
# "induserve": [{"label": "全部", "value": ""}, {"label": "产业联盟", "value": 1},
# {"label": "公共服务平台", "value": 2}, {"label": "行业协会", "value": 3},
# {"label": "院士工作站", "value": 4}, {"label": "质量检测与测量中心", "value": 5}]
# }
#
# return jsonify(code=RET.OK, msg="查询成功", options=data)
#
#
# # 太原市创新资源机构分布图
# @api_atlas.route('/innovate/distribute', methods=['POST'])
# # @login_required
# def innovate_distribute():
# '''创新资源机构分布'''
# req_dict = request.get_json()
# inid = req_dict.get("inid") # 行业id
# cate = req_dict.get("cate") # 行业等级,(高端设备等五个为"1",子行业为"2")
# district = req_dict.get("district") # 区县
#
# # 校验参数完整性
# if not all([inid, cate]):
# return jsonify(code=RET.PARAMERR, msg="参数不完整")
# try:
# name = Industry.query.filter_by(nid=inid).first().oname # 真名
# orgs = Orgs.query.with_entities(Orgs.category).distinct().all()
# category = [i[0] for i in orgs] # 拿到类型的无重复值
# data = []
# if cate == "1": # f_type
# if district:
# orgs = Orgs.query.filter_by(admin=district).filter(Orgs.navigator.like("%{}%".format(name)))
# else:
# orgs = Orgs.query.filter(Orgs.navigator.like("%{}%".format(name)))
# for cate in category:
# nums = orgs.filter_by(category=cate).count()
# data.append({"label": cate, "value": nums})
# else:
# if district:
# orgs = Orgs.query.filter_by(admin=district).filter(Orgs.navigat.like("%{}%".format(name)))
# else:
# orgs = Orgs.query.filter(Orgs.navigat.like("%{}%".format(name)))
# for cate in category:
# nums = orgs.filter_by(category=cate).count()
# data.append({"label": cate, "value": nums})
# return jsonify(code=RET.OK, msg="查询成功", data=data)
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DBERR, msg="数据库查询错误")
#
#
# # 太原市创新资源机构列表(高等院校和告高职转告合并,高职专高作为第二分类,合并两个表)
# @api_atlas.route('/innovate/orgs', methods=['POST'])
# # @login_required
# def orgs():
# '''创新资源机构列表'''
# req_dict = request.get_json()
# inid = req_dict.get("inid") # 行业id
# cate = req_dict.get("cate") # 行业等级,(高端设备等五个为"1",子行业为"2")
#
# cateone = req_dict.get("cateone") # 机构类型id. 高等院校1,科研机构2,创新平台3,产业服务平台4
# catetwo = req_dict.get("catetwo") # 机构类型2 id
# product = req_dict.get("product") # 产品
#
# page = req_dict.get("page") # 分页页码
# perpage = req_dict.get("perpage") # 分页大小
#
# # 校验参数完整性
# if not all([inid, cate, cateone, page, perpage]):
# return jsonify(code=RET.PARAMERR, msg="参数不完整")
#
# name = Industry.query.filter_by(nid=inid).first().oname
#
# if cateone == 1: # 高等院校
# try:
# if cate == "1":
# college = College.query.filter(College.navigator.like("%{}%".format(name)))
# else:
# college = College.query.filter(College.navigat.like("%{}%".format(name)))
# if catetwo:
# college = college.filter_by(cateid=catetwo)
# if product:
# college = college.filter(College.research.like("%{}%".format(product)))
# size = college.count()
# college = college.paginate(page, perpage).items
#
# data = {"df": [{"id": i.id,
# "name": i.name,
# "cate": i.category,
# "cateone": cateone} for i in college],
# "size": size}
# return jsonify(code=RET.OK, msg="查询成功", data=data)
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DATAERR, msg="参数错误")
# elif cateone == 2: # 科研机构
# if cate == "1":
# scientific = Scientific.query.filter(Scientific.navigator.like("%{}%".format(name)))
# else:
# scientific = Scientific.query.filter(Scientific.navigat.like("%{}%".format(name)))
# if product:
# scientific = scientific.filter(Scientific.research.like("%{}%".format(product)))
# size = scientific.count()
# scientific = scientific.paginate(page, perpage).items
# data = {"df": [{"id": i.id,
# "name": i.name,
# "cate": "科研机构",
# "cateone": cateone} for i in scientific],
# "size": size}
# return jsonify(code=RET.OK, msg="查询成功", data=data)
# elif cateone == 3: # 创新平台3
# if cate == "1":
# lab = Lab.query.filter(Lab.navigator.like("%{}%".format(name)))
# else:
# lab = Lab.query.filter(Lab.navigat.like("%{}%".format(name)))
# if catetwo:
# lab = lab.filter_by(cateid=catetwo)
# if product:
# lab = lab.filter(Lab.research.like("%{}%".format(product)))
# size = lab.count()
# lab = lab.paginate(page, perpage).items
# data = {"df": [{"id": i.id,
# "name": i.name,
# "cate": i.cate,
# "cateone": cateone} for i in lab],
# "size": size}
# return jsonify(code=RET.OK, msg="查询成功", data=data)
# elif cateone == 4: # 产业服务平台
# if cate == "1":
# platform = Platform.query.filter(Platform.navigator.like("%{}%".format(name)))
# else:
# platform = Platform.query.filter(Platform.navigat.like("%{}%".format(name)))
# if catetwo:
# platform = platform.filter_by(cateid=catetwo)
# if product:
# platform = platform.filter(Platform.research.like("%{}%".format(product)))
# size = platform.count()
# platform = platform.paginate(page, perpage).items
# data = {"df": [{"id": i.id,
# "name": i.name,
# "cate": i.cate,
# "cateone": cateone} for i in platform],
# "size": size}
# return jsonify(code=RET.OK, msg="查询成功", data=data)
#
# else:
# return jsonify(code=RET.PARAMERR, msg="参数错误")
#
#
# # 产业发展图谱资源机构页面的散点图地图
# @api_atlas.route('/orgs/sdmap', methods=['POST'])
# # @login_required
# def orgs_sdmap():
# req_dict = request.get_json()
# inid = req_dict.get("inid") # 行业id
# cate = req_dict.get("cate") # 行业等级,(高端设备等五个为"1",子行业为"2")
#
# cateone = req_dict.get("cateone") # 机构类型id. 高等院校1,科研机构2,创新平台3,产业服务平台4
# catetwo = req_dict.get("catetwo") # 机构类型2 id
# product = req_dict.get("product") # 产品
#
# page = req_dict.get("page") # 分页页码
# perpage = req_dict.get("perpage") # 分页大小
#
# # 校验参数完整性
# if not all([inid, cate, cateone]):
# return jsonify(code=RET.PARAMERR, msg="参数不完整")
#
# name = Industry.query.filter_by(nid=inid).first().oname
#
# if cateone == 1: # 高等院校
# try:
# if cate == "1":
# college = College.query.filter(College.navigator.like("%{}%".format(name)))
# else:
# college = College.query.filter(College.navigat.like("%{}%".format(name)))
# if catetwo:
# college = college.filter_by(cateid=catetwo)
# if product:
# college = college.filter(College.research.like("%{}%".format(product)))
#
# college = college.paginate(page, perpage).items
#
# data = [{"id": com.id,
# "name": com.name,
# "jwd": {"lng": com.lng, # 园区地址出的经纬度
# "lat": com.lat}
# } for com in college]
#
# return jsonify(code=RET.OK, msg="查询成功", data=data)
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DATAERR, msg="参数错误")
# elif cateone == 2: # 科研机构
# if cate == "1":
# scientific = Scientific.query.filter(Scientific.navigator.like("%{}%".format(name)))
# else:
# scientific = Scientific.query.filter(Scientific.navigat.like("%{}%".format(name)))
# if product:
# scientific = scientific.filter(Scientific.research.like("%{}%".format(product)))
#
# scientific = scientific.paginate(page, perpage).items
# data = [{"id": com.id,
# "name": com.name,
# "jwd": {"lng": com.lng, # 园区地址出的经纬度
# "lat": com.lat}
# } for com in scientific]
# return jsonify(code=RET.OK, msg="查询成功", data=data)
# elif cateone == 3: # 创新平台3
# if cate == "1":
# lab = Lab.query.filter(Lab.navigator.like("%{}%".format(name)))
# else:
# lab = Lab.query.filter(Lab.navigat.like("%{}%".format(name)))
# if catetwo:
# lab = lab.filter_by(cateid=catetwo)
# if product:
# lab = lab.filter(Lab.research.like("%{}%".format(product)))
#
# lab = lab.paginate(page, perpage).items
# data = [{"id": com.id,
# "name": com.name,
# "jwd": {"lng": com.lng, # 园区地址出的经纬度
# "lat": com.lat}
# } for com in lab]
#
# return jsonify(code=RET.OK, msg="查询成功", data=data)
# elif cateone == 4: # 产业服务平台
# if cate == "1":
# platform = Platform.query.filter(Platform.navigator.like("%{}%".format(name)))
# else:
# platform = Platform.query.filter(Platform.navigat.like("%{}%".format(name)))
# if catetwo:
# platform = platform.filter_by(cateid=catetwo)
# if product:
# platform = platform.filter(Platform.research.like("%{}%".format(product)))
#
# platform = platform.paginate(page, perpage).items
# data = [{"id": com.id,
# "name": com.name,
# "jwd": {"lng": com.lng, # 园区地址出的经纬度
# "lat": com.lat}
# } for com in platform]
#
# return jsonify(code=RET.OK, msg="查询成功", data=data)
#
# else:
# return jsonify(code=RET.PARAMERR, msg="参数错误")
#
#
# # 太原园区列表及所有园区的数量及面积(默认全部)
# @api_atlas.route('/carrier/garden', methods=['POST'])
# # @login_required
# def garden():
# '''创新资源机构列表'''
# req_dict = request.get_json()
# inid = req_dict.get("inid") # 行业id
# cate = req_dict.get("cate") # 行业等级,(高端设备等五个为"1",子行业为"2")
#
# page = req_dict.get("page") # 分页页码
# perpage = req_dict.get("perpage") # 分页大小
#
# keyword = req_dict.get("keyword") # 搜索园区姓名
# level = req_dict.get("level") # 园区级别
#
# # 校验参数完整性
# if not all([page, perpage]):
# return jsonify(code=RET.PARAMERR, msg="参数不完整")
#
# try:
# if inid:
# name = Industry.query.filter_by(nid=inid).first().oname # 获取导航对应的真名
# if cate == "1":
# induzone = Induzone.query.filter(Induzone.navigator.like("%{}%".format(name)))
# else:
# induzone = Induzone.query.filter(Induzone.navigat.like("%{}%".format(name)))
# else:
# induzone = Induzone.query.filter_by()
# if keyword:
# induzone = induzone.filter(Induzone.name.like("%{}%".format(keyword))) # 查询词
# if level:
# induzone = induzone.filter_by(level=level) # 园区级别筛选
# # count = induzone.count() # 园区总数
# count_x = induzone.filter_by(cate="行政区").count() # 园区总数
# count_y = induzone.filter_by(cate="产业园区").count() # 产业园区总数
# # areas = induzone.with_entities(func.sum(Induzone.area)).scalar() # 园区总面积
# size = induzone.count() # 分页总数
# induzone = induzone.paginate(page, perpage).items
#
# data = {"garden": [{"id": i.id,
# "name": i.name,
# "level": i.level if i.level else "",
# "cate": i.cate if i.cate else "",
# "cluster": i.cluster if i.cluster else ""} for i in induzone],
# "size": size,
# # "df": {"count": count,
# # "areas": round(areas, 2) if areas else "-"},
# "df": {"count_x": count_x, # 行政区数
# "count_y": count_y} # 园区数
# }
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DBERR, msg="数据库查询错误")
#
# return jsonify(code=RET.OK, msg="查询成功", data=data)
#
#
# # 太原园区列表及所有园区的数量及面积(默认全部)
# @api_atlas.route('/carrier/gardens', methods=['POST'])
# def gardens():
# '''创新资源机构列表'''
# req_dict = request.get_json()
# inid = req_dict.get("inid") # 行业id
# cate = req_dict.get("cate") # 行业等级,(高端设备等五个为"1",子行业为"2")
#
# page = req_dict.get("page") # 分页页码
# perpage = req_dict.get("perpage") # 分页大小
#
# keyword = req_dict.get("keyword") # 搜索园区姓名
# level = req_dict.get("level") # 园区级别
# clasify = req_dict.get("clasify") # 园区类别,行政区、产业园区
# # 校验参数完整性
# if not all([page, perpage, clasify]):
# return jsonify(code=RET.PARAMERR, msg="参数不完整")
#
# try:
# if inid:
# name = Industry.query.filter_by(nid=inid).first().oname # 获取导航对应的真名
# if cate == "1":
# induzone = Induzone.query.filter(Induzone.navigator.like("%{}%".format(name)))
# else:
# induzone = Induzone.query.filter(Induzone.navigat.like("%{}%".format(name)))
# else:
# induzone = Induzone.query.filter_by()
# if level:
# induzone = induzone.filter_by(level=level) # 园区级别筛选
#
# count_x = induzone.filter_by(cate="行政区").count() # 园区总数
# count_y = induzone.filter_by(cate="产业园区").count() # 产业园区总数
#
# if clasify == "行政区":
# induzone = induzone.filter_by(cate="行政区")
# elif clasify == "产业园区":
# induzone = induzone.filter_by(cate="产业园区")
#
# if keyword:
# # induzone = induzone.filter(Induzone.name.like("%{}%".format(keyword))) # 查询词
# induzone = Induzone.query.filter(Induzone.name.like("%{}%".format(keyword))) # 查询词
# size = induzone.count() # 分页总数
# induzone = induzone.paginate(page, perpage).items
#
# data = {"garden": [{"id": i.id,
# "name": i.name, # 园区名
# "level": i.level if i.level else "", # 园区级别
# "cate": i.cate if i.cate else "", # 园区类型
# "cluster": i.cluster if i.cluster else "", # 产业集群
# "address": i.address if i.address else "", # 园区地址
# "area": str(i.area) + "平方公里" if i.area else "", # 园区面积
# } for i in induzone],
# "size": size,
# "df": {"count_x": count_x, # 行政区数
# "count_y": count_y} # 园区数
# }
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DBERR, msg="数据库查询错误")
#
# return jsonify(code=RET.OK, msg="查询成功", data=data)
#
#
# # 产业发展图谱产业载体园区的散点图地图(2020-11-7)
# @api_atlas.route('/zone/sdmap', methods=['POST'])
# # @login_required
# def zone_sdmap():
# req_dict = request.get_json()
# inid = req_dict.get("inid") # 行业id
# cate = req_dict.get("cate") # 行业等级,(高端设备等五个为"1",子行业为"2")
#
# page = req_dict.get("page") # 分页页码
# perpage = req_dict.get("perpage") # 分页大小
#
# keyword = req_dict.get("keyword") # 搜索园区姓名
# level = req_dict.get("level") # 园区级别
# clasify = req_dict.get("clasify") # 园区类别,行政区、产业园区
# # 校验参数完整性
# if not all([page, perpage]):
# return jsonify(code=RET.PARAMERR, msg="参数不完整")
#
# try:
# if inid:
# name = Industry.query.filter_by(nid=inid).first().oname # 获取导航对应的真名
# if cate == "1":
# induzone = Induzone.query.filter(Induzone.navigator.like("%{}%".format(name)))
# else:
# induzone = Induzone.query.filter(Induzone.navigat.like("%{}%".format(name)))
# else:
# induzone = Induzone.query.filter_by()
# if keyword:
# induzone = induzone.filter(Induzone.name.like("%{}%".format(keyword))) # 查询词
# if level:
# induzone = induzone.filter_by(level=level) # 园区级别筛选
# if clasify == "行政区":
# induzone = induzone.filter_by(cate="行政区")
# elif clasify == "产业园区":
# induzone = induzone.filter_by(cate="产业园区")
# induzone = induzone.paginate(page, perpage).items
#
# data = [{"id": com.id,
# "name": com.name,
# "jwd": {"lng": com.lng, # 园区地址出的经纬度
# "lat": com.lat}
# } for com in induzone]
#
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DBERR, msg="数据库查询错误")
#
# return jsonify(code=RET.OK, msg="查询成功", data=data)
#
#
# '''产业下企业、资源机构及园区的色块图、散点图'''
#
#
# # 按数量进行颜色的选择
# def jisuan(num):
# if num >= 0 and num <= 10:
# return "#72D4F1"
# if num > 10 and num <= 30:
# return "#00BAF6"
# if num > 30 and num <= 50:
# return "#4F9FFF"
# if num > 50 and num <= 100:
# return "#4265F6"
# if num > 100 and num <= 200:
# return "#0052d6"
# if num > 200:
# return "#0245AE"
#
#
# # 产业发展图谱企业页面太原市的色块图地图(2020-11-7)
# @api_atlas.route('/enterprise/piecemap', methods=['POST'])
# # @login_required
# def enterprise_piecemap():
# '''获取太原市下区县企业数量色块图'''
# req_dict = request.get_json()
# inid = req_dict.get("inid") # 行业id
# cate = req_dict.get("cate") # 行业等级,
#
# if cate != "1":
# return jsonify(code=RET.PARAMERR, msg="参数错误")
# try:
# district = Company.query.filter_by(city="太原市").with_entities(Company.district).distinct().all()
# # print(district)
# district = [i[0] for i in district] # 拿到区县的无重复值
# company = Company.query.filter_by(city="太原市", f_type=inid)
# # 太原市经纬度
# tyjwd = [112.549, 37.957]
# df = list()
# for dis in district:
# data_district = company.filter_by(district=dis)
# com = Company.query.filter_by(city="太原市", district=dis).first()
# df.append({"name": dis,
# "value": data_district.count(),
# "jwd": {"lng": com.d_lng, "lat": com.d_lat}, # 区县的经纬度
# "color": jisuan(data_district.count())})
# data = {"ty": tyjwd, "df": df}
# return jsonify(code=RET.OK, msg="查询成功", data=data)
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DBERR, msg="数据库查询错误")
#
#
# # 企业坐标图例
# def get_color(s):
# iphost = "http://39.100.39.50:8006"
# # iphost = "192.168.1.127:5000"
# if s == "上游":
# return "{}/static/legend/red.png".format(iphost)
# if s == "中游":
# return "{}/static/legend/bule.png".format(iphost)
# if s == "下游":
# return "{}/static/legend/yellow.png".format(iphost)
# return "{}/static/legend/green.png".format(iphost)
#
#
# # 产业发展图谱企业页面的散点图地图(2020-11-7)
# @api_atlas.route('/enterprise/sdmap', methods=['POST'])
# # @login_required
# def enterprise_sdmap():
# '''产业发展图谱企业页面的散点图地图,1级导航必须有区县,2级导航可有可无'''
# req_dict = request.get_json()
# inid = req_dict.get("inid") # 行业id
# cate = req_dict.get("cate") # 行业等级,
# district = req_dict.get("district") # 区县
# product = req_dict.get("product") # 产品
#
# try:
# if cate != "2" and district == "":
# return jsonify(code=RET.PARAMERR, msg="参数错误le")
# if cate == "1": # 一级导航
# company = Company.query.filter_by(city="太原市", f_type=inid)
# if product:
# company = company.filter(Company.product_all.like("%{}%".format(product)))
# if district:
# company = company.filter_by(district=district)
# company = company.all()
# data = []
# for com in company:
# data.append({"id": com.id,
# "name": com.company_name,
# "jwd": {"lng": com.lng, # 企业地址出的经纬度
# "lat": com.lat},
# "stream": get_color(com.stream)}) # 上下中游
# return jsonify(code=RET.OK, msg="查询成功", data=data)
# if cate == "2": # 二级导航
# company = Company.query.filter_by(city="太原市", c_type=inid)
# if product:
# company = company.filter(Company.product_all.like("%{}%".format(product)))
# if district:
# company = company.filter_by(district=district)
# company = company.all()
# data = []
# for com in company:
# data.append({"id": com.id,
# "name": com.company_name,
# "jwd": {"lng": com.lng, # 企业地址出的经纬度
# "lat": com.lat},
# "stream": get_color(com.stream)}) # 上下中游
# return jsonify(code=RET.OK, msg="查询成功", data=data)
# else:
# return jsonify(code=RET.PARAMERR, msg="参数错误")
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DBERR, msg="数据库查询错误")
#
# # # 产业发展图谱资源机构页面的散点图地图
# # @api_atlas.route('/orgs/sdmap', methods=['POST'])
# # # @login_required
# # def orgs_sdmap():
# # '''产业发展图谱资源机构页面的散点图地图'''
# # req_dict = request.get_json()
# # inid = req_dict.get("inid") # 行业id
# # cate = req_dict.get("cate") # 行业等级,
# # district = req_dict.get("district") # 区县
# # product = req_dict.get("product") # 产品-research
# #
# # try:
# # name = Industry.query.filter_by(nid=inid, statu=1).first().oname
# # if cate == "1":
# # orgs = Orgs.query.filter(Orgs.navigator.like("%{}%".format(name)))
# # else:
# # orgs = Orgs.query.filter(Orgs.navigat.like("%{}%".format(name)))
# # if product:
# # orgs = Orgs.query.filter(Orgs.research.like("%{}%".format(product)))
# # if district:
# # orgs = orgs.filter_by(admin=district)
# # orgs = orgs.all()
# # data = []
# # for com in orgs:
# # data.append({"id": com.id,
# # "name": com.name,
# # "jwd": {"lng": com.lng, # 园区地址出的经纬度
# # "lat": com.lat}
# # })
# #
# # except Exception as e:
# # current_app.logger.error(e)
# # return jsonify(code=RET.DBERR, msg="数据库查询错误")
# # return jsonify(code=RET.OK, msg="查询成功", data=data)
#
# #
# # # 产业发展图谱产业载体园区的散点图地图(2020-11-7)
# # @api_atlas.route('/zone/sdmap', methods=['POST'])
# # # @login_required
# # def zone_sdmap():
# # '''产业发展图谱产业载体页面的散点图地图'''
# # req_dict = request.get_json()
# # inid = req_dict.get("inid") # 行业id
# # cate = req_dict.get("cate") # 行业等级,
# # district = req_dict.get("district") # 区县
# #
# # try:
# # name = Industry.query.filter_by(nid=inid, statu=1).first().oname
# # if cate == "1":
# # induzone = Induzone.query.filter(Induzone.navigator.like("%{}%".format(name)))
# # else:
# # induzone = Induzone.query.filter(Induzone.navigat.like("%{}%".format(name)))
# # if district:
# # induzone = induzone.filter_by(region=district)
# #
# # induzone = induzone.all()
# #
# # data = []
# # for com in induzone:
# # data.append({"id": com.id,
# # "name": com.name,
# # "jwd": {"lng": com.lng, # 园区地址出的经纬度
# # "lat": com.lat}
# # })
# #
# # except Exception as e:
# # current_app.logger.error(e)
# # return jsonify(code=RET.DBERR, msg="数据库查询错误")
# # return jsonify(code=RET.OK, msg="查询成功", data=data)
def industry_enterprise():
'''骨干企业数据'''
req_dict = request.get_json()
inid = req_dict.get("inid") # 行业id
industry_level = req_dict.get("industry_level") # 行业等级,(父行个为"1",子行业为"2")
product = req_dict.get("product")
page = req_dict.get("page") # 分页页码
perpage = req_dict.get("perpage") # 分页大小
# sorts = req_dict.get("sorts") # 排序 sorts "1"按时间降序 ,“2”按热度降序
# 校验参数完整性
if not all([industry_level, page, perpage]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
try:
if industry_level == 1:
company = Company.query.filter_by(f_type=inid, city="晋城市")
else:
company = Company.query.filter_by(c_type=inid, city="晋城市")
if product:
company = Company.query.filter(Company.product_all.like("%{}%".format(product)))
size = company.count()
companys = company.order_by(Company.hots.desc()).paginate(page, perpage).items # 企业热度倒序
df = [{"id": i.id,
"company_name": i.company_name,
"district": i.district,
"build_date": (i.build_date).strftime("%Y-%m-%d %H:%M:%S"),
"legal": i.legal,
"capital_nums": i.capital_nums,
"entype": i.entype,
"address": i.address,
"telephone": i.telephone,
"high_new": '高新技术企业' if i.high_new == '1' else '',
"tbe": '科技型中小企业' if i.tbe == '1' else '',
"quoted_company": '上市企业' if i.quoted_company == '1' else '',
"zjtg": '精专特新企业' if i.zjtg == '1' else '',
"unicorn": '独角兽企业' if i.unicorn == '1' else '',
"dengl": '瞪羚企业' if i.dengl == '1' else '',
"isfive": '五百强企业' if i.isfive == '1' else '',
"scale": '规模以上企业' if i.scale == '1' else ''
} for i in companys]
data = {"size": size, "df": df}
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
return jsonify(code=RET.OK, msg="获取成功", data=data)
# 点击产业创新资源联动显示 innovation resource
@api_atlas.route('/innovate/resource', methods=['POST'])
def industry_resource():
'''创新资源机构列表'''
req_dict = request.get_json()
inid = req_dict.get("inid") # 行业id
industry_level = req_dict.get("industry_level") # 行业等级,(父行业高端设备等五个为"1",子行业为"2")
select_flag = req_dict.get("select_flag") # 机构类型id. 高等院校1,科研机构2,创新平台3,产业服务平台4
page = req_dict.get("page") # 分页页码
perpage = req_dict.get("perpage") # 分页大小
# 校验参数完整性
if not all([inid, industry_level, select_flag, page, perpage]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
name = Industry.query.filter_by(nid=inid).first().oname
if select_flag == 1: # 高等院校
try:
if industry_level == 1:
college = College.query.filter(College.navigator.like("%{}%".format(name)))
else:
college = College.query.filter(College.navigat.like("%{}%".format(name)))
size = college.count()
college = college.paginate(page, perpage).items
data = {"df": [{"id": i.id,
"name": i.name,
"admin": i.admin,
"buildate": i.buildate,
"charge": i.charge,
"cate": i.category,
"nature": i.nature,
"ccode": i.ccode,
"address": i.address,
} for i in college],
"size": size}
return jsonify(code=RET.OK, msg="查询成功", data=data)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DATAERR, msg="参数错误")
elif select_flag == 2: # 科研机构
if industry_level == 1:
scientific = Scientific.query.filter(Scientific.navigator.like("%{}%".format(name)))
else:
scientific = Scientific.query.filter(Scientific.navigat.like("%{}%".format(name)))
size = scientific.count()
scientific = scientific.paginate(page, perpage).items
data = {"df": [{"id": i.id,
"name": i.name,
"admin": i.admin,
"telephone": i.telephone,
"fax": i.fax,
"postcode": i.postcode,
"address": i.address} for i in scientific],
"size": size}
return jsonify(code=RET.OK, msg="查询成功", data=data)
elif select_flag == 3: # 创新平台3
if industry_level == 1:
lab = Lab.query.filter(Lab.navigator.like("%{}%".format(name)))
else:
lab = Lab.query.filter(Lab.navigat.like("%{}%".format(name)))
size = lab.count()
lab = lab.paginate(page, perpage).items
data = {"df": [{"id": i.id,
"name": i.name,
"admin": i.admin,
"cate": i.cate,
"fax": i.fax,
"postcode": i.postcode,
"address": i.address} for i in lab],
"size": size}
return jsonify(code=RET.OK, msg="查询成功", data=data)
else:
return jsonify(code=RET.PARAMERR, msg="参数错误")
def get_data(name, industry_level, select_flag, page, perpage):
try:
if select_flag in [1, 2]: # 当选择行政区/园区时
if select_flag == 1 and industry_level == 1: # 当选择的是父产业的行政区时
induzone = Induzone.query.filter(Induzone.cate.like('行政区'), Induzone.navigator.like("%{}%".format(name)))
elif select_flag == 1 and industry_level == 2: # 当选择的是子产业的行政区时
induzone = Induzone.query.filter(Induzone.cate.like('行政区'), Induzone.navigat.like("%{}%".format(name)))
elif select_flag == 2 and industry_level == 1: # 当选择的是父产业的园区时
induzone = Induzone.query.filter(Induzone.cate.like('产业园区'), Induzone.navigator.like("%{}%".format(name)))
elif select_flag == 2 and industry_level == 2: # 当选择的是父产业的园区时
induzone = Induzone.query.filter(Induzone.cate.like('产业园区'), Induzone.navigat.like("%{}%".format(name)))
size = induzone.count() # 分页总数
induzone = induzone.paginate(page, perpage).items
if select_flag == 1:
# 封装行政区数据
admin_data = {"admin_data": [{
"id": i.id,
"image": i.image,
# "region": i.region,
"region": i.district,
"cate": i.cate, # 园区类型
"area": i.area,
"address": i.address,
"cluster": i.cluster} for i in induzone],
"size": size}
return admin_data
if select_flag == 2:
# 封装园区数据
garden_data = {"garden": [{"id": i.id,
"name": i.name, # 园区名称
"region": i.region, # 所属地区
"phone": i.phone, # 联系电话
"level": i.level, # 园区级别
"cate": i.cate, # 园区类型
"address": i.address, } for i in induzone], # 园区地址
"size": size}
return garden_data
if select_flag == 3: # 当选择载体土地时
if industry_level == 1: # 当选择的是父产业时
land = ZaitiLand.query.filter(ZaitiLand.navigator.like("%{}%".format(name)))
else:
land = ZaitiLand.query.filter(ZaitiLand.navigat.like("%{}%".format(name)))
size = land.count() # 分页总数
land = land.paginate(page, perpage).items
# 封装土地数据
land_data = {"land_data": [{
"id": i.id,
"name": i.name,
"num": i.num,
"nature": i.nature,
"acreage": i.acreage,
"industry_type": i.industry_type,
"telephone": i.telephone
} for i in land], "size": size}
return land_data
if select_flag == 4: # 当选择载体楼宇时
if industry_level == 1: # 当选择的是父产业时
build = ZaitiBuild.query.filter(ZaitiBuild.navigator.like("%{}%".format(name)))
else:
build = ZaitiBuild.query.filter(ZaitiBuild.navigat.like("%{}%".format(name)))
size = build.count() # 分页总数
build = build.paginate(page, perpage).items
# 封装楼宇数据
build_data = {
"build_data": [{
"id": i.id,
"name": i.name,
"acreage": i.acreage,
"buide_type": i.buide_type,
"industry_type": i.industry_type,
"telephone": i.telephone,
"addr": i.addr,
} for i in build], "size": size
}
return build_data
if select_flag == 5: # 当选择载体厂房时
if industry_level == 1: # 当选择的是父产业时
factory = ZaitiFactory.query.filter(ZaitiFactory.navigator.like("%{}%".format(name)))
else:
factory = ZaitiFactory.query.filter(ZaitiFactory.navigat.like("%{}%".format(name)))
size = factory.count() # 分页总数
factory = factory.paginate(page, perpage).items
# 封装楼宇数据
factory_data = {
"factory_data": [{
"id": i.id,
"name": i.name,
"acreage": i.acreage,
"factory_type": i.factory_type,
"industry_type": i.industry_type,
"telephone": i.telephone,
"addr": i.addr,
} for i in factory], "size": size
}
return factory_data
except Exception as e:
print(e)
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
# 产业载体
@api_atlas.route('/carrier/zaiti', methods=['POST'])
def industry_zaiti():
'''产业载体数据'''
req_dict = request.get_json()
inid = req_dict.get("inid") # 行业id
industry_level = req_dict.get("industry_level") # 行业等级,(父行业高端设备等五个为"1",子行业为"2")
select_flag = req_dict.get("select_flag") # 1为行政区,2为园区,3为产业载体,4为土地,5为楼宇,6为厂房
page = req_dict.get("page") # 分页页码
perpage = req_dict.get("perpage") # 分页大小
# 校验参数完整性
if not all([page, perpage]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
# if inid:
name = Industry.query.filter_by(nid=inid).first().oname # 获取导航对应的真名
try:
data = get_data(name, industry_level, select_flag, page, perpage)
return jsonify(code=RET.OK, msg="数据查询成功", data=data)
except Exception as e:
current_app.logger.error(e)
# 产业政策
@api_atlas.route('/industry/indus_policy', methods=['POST'])
def industry_policy():
"""产业政策数据"""
req_dict = request.get_json()
inid = req_dict.get("inid") # 行业id
industry_level = req_dict.get("industry_level") # 行业等级,(父行业高端设备等五个为"1",子行业为"2")
page = req_dict.get("page") # 分页页码
perpage = req_dict.get("perpage") # 分页大小
# 校验参数完整性
if not all([page, perpage]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
try:
indu_policy = ''
size = ''
name = Industry.query.filter_by(nid=inid).first().oname # 获取导航对应的真名
if industry_level == 1:
indu_policy = InduPolicy.query.filter(InduPolicy.navigator.like("%{}%".format(name)))
size = indu_policy.count() # 分页总数
indu_policy = indu_policy.paginate(page, perpage).items
if industry_level == 2:
indu_policy = InduPolicy.query.filter(InduPolicy.navigat.like("%{}%".format(name)))
size = indu_policy.count() # 分页总数
indu_policy = indu_policy.paginate(page, perpage).items
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
# 封装政策数据
policy_data = {
"policy_data": [{
"id": i.id,
"name": i.name,
"org": i.org,
"pubdate": (i.pubdate).strftime("%Y-%m-%d %H:%M:%S")
} for i in indu_policy],
"size": size
}
return jsonify(code=RET.OK, msg="政策数据查询成功", data=policy_data)
# 产业政策详情信息-复用招商驾驶舱政策详情接口
# 骨干企业详情信息
# 创新资源-高等院校详情
@api_atlas.route('/innovate/college_detail', methods=['POST'])
def get_college_detail():
req_dict = request.get_json()
college_id = req_dict.get('id')
try:
college = College.query.filter_by(id=college_id).first()
# 封装院校数据
data = {
"name": college.name, # 校名
"charge": college.charge, # 主管部门
"buildate": college.buildate, # 创办时间
"nature": college.nature, # 办学性质
"clas": college.clas, # 学校类别
"address": college.address, # 校址
"introduct": college.introduct, # 简介
"ccode": college.ccode, # 学校代码
"feature": college.feature, # 学校特色
"research": college.research, # 研究方向
"major": college.major,
"faculty": college.faculty,
"lng": college.lng, # 经度
"lat": college.lat # 纬度
}
return jsonify(code=RET.OK, msg='院校详情查询成功!', data=data)
except Exception as e:
current_app.logger.error(e)
# 创新资源-科研机构详情
@api_atlas.route('/innovate/scientific_detail', methods=['POST'])
def get_scientific_detail():
req_dict = request.get_json()
scientific_id = req_dict.get('id')
try:
scientific = Scientific.query.filter_by(id=scientific_id).first()
# 封装科研机构数据
data = {
"name": scientific.name, # 名称
"admin": scientific.admin, # 行政区
"telephone": scientific.telephone, # 联系电话
"fax": scientific.fax, # 传真
"postcode": scientific.postcode, # 邮编
"address": scientific.address, # 地址
"introduct": scientific.introduct, # 简介
"lng": scientific.lng, # 经度
"lat": scientific.lat # 纬度
}
return jsonify(code=RET.OK, msg='科研机构详情查询成功!', data=data)
except Exception as e:
current_app.logger.error(e)
# 创新资源-创新平台详情
@api_atlas.route('/innovate/Lab_detail', methods=['POST'])
def get_lab_detail():
req_dict = request.get_json()
lab_id = req_dict.get('id')
try:
lab = Lab.query.filter_by(id=lab_id).first()
# 封装创新平台数据
data = {
"name": lab.name, # 名称
"address": lab.address, # 地址
"introduct": lab.introduct, # 简介
"lng": lab.lng, # 经度
"lat": lab.lat # 纬度
}
return jsonify(code=RET.OK, msg='创新平台详情查询成功!', data=data)
except Exception as e:
current_app.logger.error(e)
# 产业载体-各类型详情信息
@api_atlas.route('/carrier/zaiti_detail', methods=['POST'])
def get_zaiti_detail_data():
req_dict = request.get_json()
id = req_dict.get('id')
cate_id = req_dict.get('cate_id') # 1为行政区,2为园区,3为土地,4为楼宇,5为厂房
print(cate_id)
if cate_id in [1, 2]:
try:
induzone = Induzone.query.filter_by(id=id).first()
data = {
"district": induzone.district,
"cate": induzone.cate,
"area": induzone.area,
"address": induzone.address,
"cluster": induzone.cluster,
"name": induzone.name, # 名称
# "district": induzone.district, # 所属地区
"phone": induzone.phone, # 电话
"email": induzone.email,
# "address": induzone.address, # 园区地址
"industry_position": induzone.industry_position, # 产业定位
# "cate": induzone.cate, # 园区类型
"gdp": induzone.gdp, # GDP
"represent": induzone.represent, # 代表企业
"introduct": induzone.introduct, # 简介
"level": induzone.level, # 等级
"charge": induzone.charge, # 园区负责人
"site": induzone.site, # 园区所在地
"industry_type": induzone.industry_type, # 产业类型
# "area": induzone.area, # 面积
"out_power": induzone.out_power, # 产出强度(万元/亩)
"invest_power": induzone.invest_power, # 亩均投资强度(万元/亩)
"value_product": induzone.value_product, # 亩均年产值(万元/亩)
"tax": induzone.tax, # 亩均年税收(万元/亩)
"indu_land": induzone.indu_land, # 工业土地均价(万元/亩)
"comm_land": induzone.comm_land, # 商办土地均价(万元/亩)
"highmag": induzone.highmag, # 高层管理人员(元/月)
"middlemag": induzone.middlemag, # 中级管理人员(元/月)
"worker": induzone.worker, # 普通员工(元/月)
"trans_facility": induzone.trans_facility, # 交通配套
"goods_trans": induzone.goods_trans, # 货物运输
"live_facility": induzone.live_facility, # 园区生活配套
"market": induzone.market, # 百货商场
"hotel_bus": induzone.hotel_bus, # 酒店商务
"medical": induzone.medical, # 医疗机构
"education": induzone.education, # 教育教育
}
return jsonify(code=RET.OK, msg='详情数据查询成功!', data=data)
except Exception as e:
current_app.logger.error(e)
if cate_id == 3:
try:
land = ZaitiLand.query.filter_by(id=id).first()
data = {
"num": land.num, # 编号
"name": land.name, # 地块名称
"addr": land.addr, # 地址
"nature": land.nature, # 土地性质
"acreage": land.acreage, # 面积
"target": land.target, # 规划指标
"age_limit": land.age_limit, # 出让年限
"industry_type": land.industry_type, # 产业类型
"telephone": land.telephone # 电话
}
return jsonify(code=RET.OK, msg='土地详情查询成功!', data=data)
except Exception as e:
current_app.logger.error(e)
if cate_id == 4:
try:
build = ZaitiBuild.query.filter_by(id=id).first()
data = {
"name": build.name, # 楼宇名称
"addr": build.addr, # 地址
"acreage": build.acreage, # 面积
"buide_type": build.buide_type, # 楼宇类型
"industry_type": build.industry_type, # 产业类型
"rate": build.rate, # 出租率
"telephone": build.telephone # 电话
}
return jsonify(code=RET.OK, msg='楼宇详情查询成功!', data=data)
except Exception as e:
current_app.logger.error(e)
if cate_id == 5:
try:
factory = ZaitiFactory.query.filter_by(id=id).first()
data = {
"name": factory.name, # 厂房名称
"addr": factory.addr, # 地址
"acreage": factory.acreage, # 面积
"structure": factory.structure, # 简介
"height": factory.height, # 高度
"bearing": factory.bearing, # 承重
"new_level": factory.new_level, # 新旧程度
"other": factory.other, # 其他
"industry_type": factory.industry_type, # 产业类型
"factory_type": factory.factory_type, # 厂房类型
"telephone": factory.telephone, # 电话
}
return jsonify(code=RET.OK, msg='厂房详情查询成功!', data=data)
except Exception as e:
current_app.logger.error(e)
import json
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from flask import current_app, request, jsonify
from apps.models import *
from apps.atlas import api_atlas
from apps.util import login_required, verify_token
from apps.utils.response_code import RET
# 企业信息详情
@api_atlas.route('/enterprise/detail', methods=['POST'])
@login_required
def enterprise_detail():
'''
企业信息详情
:return:
'''
# 获取用户id
token = request.headers["token"]
user = verify_token(token)
user_id = user.id # 用户id
req_dict = request.get_json()
_id = req_dict.get("id") # 企业id
# 校验参数完整性
if not all([_id]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
try:
company = Company.query.get(_id)
user = User.query.get(user_id) # 获取关注列表
if user:
company_ids = [coms.id for coms in user.company]
else:
company_ids = []
if company:
data = {"id": company.id,
"company_name": company.company_name,
"telephone": company.telephone if company.telephone else "-",
"web_site": company.web_site if company.web_site else "-",
"email": company.email if company.email else "-",
"address": company.address if company.address else "-",
"jwd": {"lng": company.lng if company.lng else "-",
"lat": company.lat if company.lat else "-"},
"company_info": company.company_info if company.company_info else "-",
"high_new": "高新技术企业" if company.high_new == "1" else "",
"isfive": "500强企业" if company.isfive == "1" else "", # 500强
"quoted_company": "上市企业" if company.quoted_company == "1" else "", # 上市企业
"tbe": "科技型中小企业" if company.tbe == "1" else "", # 科技型中小企业
"unicorn": "独角兽企业" if company.unicorn == "1" else "", # 独角兽企业
"dengl": "瞪羚企业" if company.dengl == "1" else "", # 瞪羚企业
"legal": company.legal if company.legal else "-",
"status": company.status if company.status else "-",
"build_date": str(company.build_date)[:10] if company.build_date else "-",
"capital": company.capital if company.capital else "-",
"social_code": company.social_code if company.social_code else "-",
"taking": company.takingn if company.takingn else "-",
"bao": company.bao_num if company.bao_num else "-",
"entype": company.entype if company.entype else "-",
"industry": company.company_industry if company.company_industry else "-",
"scope": company.business_scope if company.business_scope else "-",
"collect": "1" if company.id in company_ids else "2", # 关注状态码1关注,2未关注
"choice": "1" # 1太原企业,2全国企业
}
else:
return jsonify(code=RET.NODATA, msg="查无数据")
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
return jsonify(code=RET.OK, msg="获取成功", data=data)
# 企业收藏与取消
@api_atlas.route('/enterprise/collect', methods=['POST'])
@login_required
def enter_collect():
'''
企业收藏与取消
:return:
'''
# 获取用户id
token = request.headers["token"]
user = verify_token(token)
user_id = user.id # 用户id
# user_id = 1
req_dict = request.get_json()
_id = req_dict.get("id") # 企业id
choice = req_dict.get("choice") # 1太原企业,2全国企业
collect = req_dict.get("collect") # 关注状态(1是,2否)
# 校验参数完整性
if not all([_id, choice, collect]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
try:
if choice == "1": # 太原企业
if collect == "2": # 未关注,我要关注
user = User.query.get(user_id)
coms = Company.query.get(_id)
user.company.append(coms)
db.session.commit()
return jsonify(code=RET.OK, msg="收藏成功", collect="1")
elif collect == "1": # 已关注,我要取关
user = User.query.get(user_id)
coms = Company.query.get(_id)
user.company.remove(coms)
db.session.commit()
return jsonify(code=RET.OK, msg="取消收藏", collect="2")
else:
return jsonify(code=RET.DATAERR, msg="参数异常")
if choice == "2": # 全国企业
if collect == "2": # 未关注,我要关注
user = User.query.get(user_id)
enters = Enterprise.query.get(_id)
user.enterprise.append(enters)
db.session.commit()
return jsonify(code=RET.OK, msg="收藏成功", collect="1")
elif collect == "1": # 已关注,我要取关
user = User.query.get(user_id)
enters = Enterprise.query.get(_id)
user.enterprise.remove(enters)
db.session.commit()
return jsonify(code=RET.OK, msg="取消收藏", collect="2")
else:
return jsonify(code=RET.DATAERR, msg="状态参数异常")
else:
return jsonify(code=RET.DATAERR, msg="企业类别参数异常")
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
# 资源机构详情
@api_atlas.route('/orgs/detail', methods=['POST'])
# @login_required
def orgs_detail():
'''
资源机构详情
:return:
'''
req_dict = request.get_json()
_id = req_dict.get("id") # 机构id
cate = req_dict.get("cateone") # 机构类型
# 校验参数完整性
if not all([_id, cate]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
try:
# 高等院校
if cate == 1:
college = College.query.get(_id)
if college:
data = {"id": college.id,
"name": college.name, # 名称
"charge": college.charge if college.charge else "-", # 主管部门
"category": college.category if college.category else "-", # 学校类型
"buildate": str(college.buildate) if college.buildate else "-", # 创办时间
"nature": college.nature if college.nature else "-", # 办学性质
"address": college.address if college.address else "-", # 地址
"clas": college.clas if college.clas else "-", # 学校类别
"ccode": college.ccode if college.ccode else "-", # 学校代码
"major": college.major if college.major else "-", # 专业
"faculty": college.faculty if college.faculty else "-", # 院系设置
"feature": college.feature if college.feature else "-", # 学校特色
"introduct": college.introduct if college.introduct else "-", # 简介
"research": college.research if college.research else "-", # 研究方向
"jwd": {"lng": college.lng if college.lng else "-",
"lat": college.lat if college.lat else "-"}
}
return jsonify(code=RET.OK, msg="获取成功", data=data)
else:
return jsonify(code=RET.NODATA, msg="无数据")
# 科研机构
elif cate == 2:
college = Scientific.query.get(_id)
if college:
data = {"id": college.id,
"name": college.name, # 机构名称
"telephone": college.telephone if college.telephone else "-", # 电话
"fax": college.fax if college.fax else "-", # 传真
"address": college.address if college.address else "-", # 地址
"postcode": college.postcode if college.postcode else "-", # 邮编
"introduct": college.introduct if college.introduct else "-", # 机构简介
"jwd": {"lng": college.lng if college.lng else "-",
"lat": college.lat if college.lat else "-"}
}
return jsonify(code=RET.OK, msg="获取成功", data=data)
else:
return jsonify(code=RET.NODATA, msg="无数据")
# 创新平台
elif cate == 3:
college = Lab.query.get(_id)
if college:
data = {"id": college.id,
"name": college.name, # 平台名称
"introduct": college.introduct if college.introduct else "-",
"address": college.address if college.address else "-", # 地址
"jwd": {"lng": college.lng if college.lng else "-",
"lat": college.lat if college.lat else "-"}
}
return jsonify(code=RET.OK, msg="获取成功", data=data)
else:
return jsonify(code=RET.NODATA, msg="无数据")
# 产业服务平台
elif cate == 4:
college = Platform.query.get(_id)
if college:
data = {"id": college.id,
"name": college.name,
"introduct": college.introduct if college.introduct else "-",
"address": college.address if college.address else "-",
"research": college.research if college.research else "-",
"jwd": {"lng": college.lng if college.lng else "-",
"lat": college.lat if college.lat else "-"}
}
return jsonify(code=RET.OK, msg="获取成功", data=data)
else:
return jsonify(code=RET.NODATA, msg="无数据")
else:
return jsonify(code=RET.DATAERR, msg="参数错误")
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
# print(get_img_url("690a08cb0aa94b7498ba13b549ee2deb"))
# 太原园区详情
@api_atlas.route('/carrier/detail', methods=['POST'])
# @login_required
def garden_detail():
req_dict = request.get_json()
_id = req_dict.get("id") # 园区id
# 校验参数完整性
if not all([_id]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
try:
iz = Induzone.query.get(_id)
if iz:
data = {"id": iz.id,
"name": iz.name, # 园区名
"image": str(iz.image), # 园区图片
"level": iz.level, # 园区级别
"cate": iz.cate, # 园区类型
"charge": iz.charge if iz.charge else "-", # 负责人
"phone": iz.phone if iz.phone else "-", # 联系电话
"address": iz.address if iz.address else "-", # 所在地
"cluster": iz.cluster if iz.cluster else "-", # 产业集群
"detail": {"acreage": str(iz.area) + "平方公里" if iz.area else "-", # 占地面积
"actarea": str(iz.actarea) + "平方公里" if iz.actarea else "-", # 建成面基
"tax": str(iz.tax) + "万元/亩" if iz.tax else "-", # 税收要求
"out_power": str(iz.out_power) + "万元/亩" if iz.out_power else "-", # 产出强度
"invest_power": str(iz.invest_power) + "万元/亩" if iz.invest_power else "-", # 投资强度
"indu_need": iz.indu_need if iz.indu_need else "-", # 行业要求
"gdp": str(iz.gdp) + "亿元" if iz.gdp else "-", # gdp
"fiscal": str(iz.fiscal) + "亿元" if iz.fiscal else "-", # 财政收入(亿元)
"indu_land": iz.indu_land if iz.indu_land else "-", # 工业土地均价
"indu_sup": iz.indu_sup if iz.indu_sup else "-", # 工业土地供应量
"comm_land": iz.comm_land if iz.comm_land else "-", # 商办土地均价
"comm_sup": iz.comm_sup if iz.comm_sup else "-", # 商办土地供应量
"represent": iz.represent if iz.represent else "-" # 代表企业
},
"invest": {"resident_ele_one": iz.resident_ele_one + "元/度" if iz.resident_ele_one else "-", # 居民电价一
"resident_ele_two": iz.resident_ele_two + "元/度" if iz.resident_ele_two else "-", # 居民电价二
"resident_ele_thr": iz.resident_ele_thr + "元/度" if iz.resident_ele_thr else "-", # 居民电价三
"comm_ele_one": iz.comm_ele_one + "元/度" if iz.comm_ele_one else "-", # 商业用电1
"comm_ele_two": iz.comm_ele_two + "元/度" if iz.comm_ele_two else "-", # 商业用电2
"comm_ele_thr": iz.comm_ele_thr + "元/度" if iz.comm_ele_thr else "-", # 商业用电3
"indu_ele_one": iz.indu_ele_one + "元/度" if iz.indu_ele_one else "-", # 工业用电1
"indu_ele_two": iz.indu_ele_two + "元/度" if iz.indu_ele_two else "-", # 工业用电2
"indu_ele_thr": iz.indu_ele_thr + "元/度" if iz.indu_ele_thr else "-", # 工业用电3
"resident_water_one": iz.resident_water_one + "元/吨" if iz.resident_water_one else "-",
# 居民用水1
"resident_water_two": iz.resident_water_two + "元/吨" if iz.resident_water_two else "-",
# 居民用水2
"resident_water_thr": iz.resident_water_thr + "元/吨" if iz.resident_water_thr else "-",
# 居民用水3
"comm_water": iz.comm_water + "元/吨" if iz.comm_water else "-", # 商业用水
"indu_water": iz.indu_water + "元/吨" if iz.indu_water else "-", # 工业用水
"special_water": iz.special_water + "元/吨" if iz.special_water else "-", # 特殊用水
"resident_natgas_one": iz.resident_natgas_one + "元/m³" if iz.resident_natgas_one else "-",
# 居民用气1
"resident_natgas_two": iz.resident_natgas_two + "元/m³" if iz.resident_natgas_two else "-",
# 居民用气1
"resident_natgas_thr": iz.resident_natgas_thr + "元/m³" if iz.resident_natgas_thr else "-",
# 居民用气1
"sewage": iz.sewage + "元/吨" if iz.sewage else "-", # 污水处理
"wagelevel": iz.wagelevel + "元/月" if iz.wagelevel else "-", # 最低工资
"worker": iz.worker + "元/月" if iz.worker else "-", # 普通员工
"middlemag": iz.middlemag + "元/月" if iz.middlemag else "-", # 中级管理
"highmag": iz.highmag + "元/月" if iz.highmag else "-", # 高级管理
},
"config": {"dis_freight": iz.dis_freight if iz.dis_freight else "-", # 距离货运站距离
"dis_port": iz.dis_port if iz.dis_port else "-", # 距离港口距离
"dis_rail": iz.dis_rail if iz.dis_rail else "-", # 距离高铁距离
"dis_air": iz.dis_air if iz.dis_air else "-", # 距离机场距离
"road_trans": iz.road_trans if iz.road_trans else "-", # 公路运输
"rail_trans": iz.rail_trans if iz.rail_trans else "-", # 铁路运输
"live_facility": iz.live_facility if iz.live_facility else "-", # 园区生活配套
"market": iz.market if iz.market else "-", # 百货
"hotel_bus": iz.hotel_bus if iz.hotel_bus else "-", # 酒店商务
"medical": iz.medical if iz.medical else "-", # 医疗
"education": iz.education if iz.education else "-" # 教育
},
"indevo": {"induenterprise": iz.induenterprise if iz.induenterprise else "-", # 规模以上企业
"innovate": iz.innovate if iz.innovate else "-", # 科研机构
"base": iz.base if iz.base else "-", # 双创基地
"carrier": iz.carrier if iz.carrier else "-", # 产业载体
}, # 产业发展
"intriduce": iz.introduct if iz.introduct else "-", # 园区介绍
"jwd": {"lng": iz.lng if iz.lng else "-", # 经度
"lat": iz.lat if iz.lat else "-"}
}
return jsonify(code=RET.OK, msg="查询成功", data=data)
else:
return jsonify(code=RET.PARAMERR, msg="参数错误")
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
import json
import requests
from sqlalchemy import or_
from flask import g, current_app, request, jsonify, session
from apps.atlas import api_atlas
from apps.util import login_required
from apps.utils.response_code import RET
from apps.models import *
# 创建body
def create_body(page, page_size, query, args_term, args_cate, args_org):
'''
:param page:
:param page_size:
:param args_query:
:param args_date:
:param args_term:
:return:
https://www.cnblogs.com/yjf512/p/4897294.html
'''
if query:
body = {
"query": {
"bool": {
"must": [{"multi_match": {"query": "{}".format(query),
# "type": "best_fields",
"fields": [
"name^1000.0",
"body^1.0",
# "org^5.0",
# "navigator^5.0",
# "navigat^5.0"
],
"tie_breaker": 0.3
}
}
]
}
},
"from": (page - 1) * page_size,
"size": page_size,
"sort": {},
"aggs": {},
"_source": [
"name", "org", "pubdate", "policyid"
],
"highlight": {}
}
else:
body = {
"query": {
"bool": {
"must": [{"match_all": {}
}
]
}
},
"from": (page - 1) * page_size,
"size": page_size,
"sort": {"pubdate": {"order": "desc"}},
"aggs": {},
"_source": [
"name", "org", "pubdate", "policyid"
],
"highlight": {}
}
if args_cate:
body["query"]["bool"]["must"].append(
{"multi_match": {"query": "{}".format(args_cate["indu"]), # match_phrase来实现完全匹配查询(精准模糊查询)。
"type": "phrase",
"fields": [
"navigator^5.0",
"navigat^5.0"
],
"slop": 0,
}
})
if args_org:
body["query"]["bool"]["must"].append(
{"multi_match": {"query": "{}".format(args_org["org"]), # match_phrase来实现完全匹配查询(精准模糊查询)。
"type": "phrase",
"fields": [
"org"
],
"slop": 0,
}
})
for k, v in args_term.items():
body["query"]["bool"]["must"].append({"term": {"{}".format(k): "{}".format(v)}})
# print(body)
return body
# 机构省市区选择(2021-1-7)
@api_atlas.route("/selectArea", methods=['GET'])
def select_area():
'''机构省市区选择'''
result = [{"label": "国家", "value": 5}, {"label": "省级", "value": 1}, {"label": "市级", "value": 2},
{"label": "区县", "value": 3}, {"label": "开发区", "value": 4}]
return jsonify(code=RET.OK, msg="查询成功", data=result)
# 发布机构(根据省市区获取)(2021-1-7)
@api_atlas.route("/areaCategory", methods=['POST'])
def area_category():
'''发布机构'''
req_dict = request.get_json()
vau = req_dict.get("vau") # 省1、市2、区县3、开发区4
# 校验参数完整性
if not all([vau]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
country = ["国务院"]
# province = ["山西省政府", "省政府办公厅", "省发展和改革委员会", "省科学技术厅", "省工业和信息化厅", "省人力资源和社会保障厅", "省生态环境厅", "省商务厅", "其他"]
province = ["山西省委", "山西省政府"]
# city = ["太原市政府", "市政府办公厅", "市发展改革委", "市科技局", "市工信局", "市人社局", "市生态环境局", "市商务局", "市文旅局", "市外来投资局", "市大数据局", "其他"]
city = ["太原市委", "太原市政府"]
district = ["小店区政府", "迎泽区政府", "杏花岭区政府", "尖草坪区政府", "万柏林区政府", "晋源区政府", "古交市政府", "清徐县政府", "阳曲县政府", "娄烦县政府", "其他"]
dev = ["山西转型综合改革示范区", "中北高新区", "清徐经济开发区", "阳曲现代农业产业示范区", "西山生态文化旅游示范区", "其他"]
if vau == 5: # 国家
result = [{"label": name, "value": country.index(name)} for name in country]
elif vau == 1: # 省,默认
result = [{"label": name, "value": province.index(name)} for name in province]
elif vau == 2: # 市
result = [{"label": name, "value": city.index(name)} for name in city]
elif vau == 3: # 区
result = [{"label": name, "value": district.index(name)} for name in district]
elif vau == 4: # 县
result = [{"label": name, "value": dev.index(name)} for name in dev]
else:
return jsonify(code=RET.DATAERR, msg="参数错误")
return jsonify(code=RET.OK, msg="查询成功", data=result)
'''
url = "http://127.0.0.1:9200/typolicy/_search"
'''
# 太原产业政策列表(转es)(小程序调用,不可删除)
@api_atlas.route('/industry/policy', methods=['POST'])
# @login_required
def indupolicy():
'''
太原产业政策列表(第一版用mysql,全文搜索,准备改用用es)
根据条件多字段搜索
:return:model-InduPolicy
'''
req_dict = request.get_json()
inid = req_dict.get("inid") # 行业id
category = req_dict.get("category") # 政策类型
org = req_dict.get("org") # 发布机构
year = req_dict.get("year") # 发布年份
keyword = req_dict.get("keyword") # 搜索园区内容
page = req_dict.get("page") # 分页页码
perpage = req_dict.get("perpage") # 分页大小
if org == "省级":
org = "山西省政府"
if org == "市级":
org = "太原市政府"
if org == "区县":
org = "小店区政府"
if org == "开发区":
org = "山西省转型综合改革示范区"
if org == "山西转型综合改革示范区":
org = "山西省转型综合改革示范区"
# 校验参数完整性
if not all([page, perpage]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
query = "" # 要查询的关键词
args_term = dict() # 要匹配的字段
args_cate = dict() # 要多字段(两导航)完全匹配
args_org = dict() # 要多字段(两导航)完全匹配
if keyword:
query = keyword
if category:
args_term["category"] = category
if org:
args_org["org"] = org
if year:
args_term["year"] = year
if inid:
indu_name = Industry.query.filter_by(nid=inid).first().oname
args_cate["indu"] = indu_name
body = create_body(page, perpage, query, args_term, args_cate, args_org)
try:
url = "http://127.0.0.1:9200/typolicy/_search"
# url = "http://127.0.0.1:9200/newindex/_search"
result_es = json.loads(requests.post(url=url, json=body).text)
# print(result_es)
data = []
size = result_es["hits"]["total"]
for item in result_es["hits"]["hits"]:
data.append({"name": item["_source"]["name"],
"org": item["_source"]["org"],
"pubdate": str(item["_source"]["pubdate"]),
"id": item["_source"]["policyid"]})
result = {"data": data, "size": size}
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
return jsonify(code=RET.OK, msg="查询成功", data=result)
# # 太原产业政策列表(转es)(pc更新)
# @api_atlas.route('/industry/policyList', methods=['POST'])
# # @login_required
# def policy_list():
# '''
# 太原产业政策列表(第一版用mysql,全文搜索,准备改用用es)
# 根据条件多字段搜索
# :return:model-InduPolicy
# '''
# req_dict = request.get_json()
#
# inid = req_dict.get("inid") # 行业id
#
# category = req_dict.get("category") # 政策类型
# level = req_dict.get("level") # 发布级别
# org = req_dict.get("org") # 发布机构
# year = req_dict.get("year") # 发布年份
# keyword = req_dict.get("keyword") # 搜索园区内容
#
# page = req_dict.get("page") # 分页页码
# perpage = req_dict.get("perpage") # 分页大小
#
# if org == "省级":
# org = "山西省政府"
# if org == "市级":
# org = "太原市政府"
# if org == "区县":
# org = "小店区政府"
# if org == "开发区":
# org = "山西转型综合改革示范区"
# if org == "山西转型综合改革示范区":
# org = "山西省转型综合改革示范区"
#
# # 校验参数完整性
# if not all([page, perpage]):
# return jsonify(code=RET.PARAMERR, msg="参数不完整")
#
# query = "" # 要查询的关键词
# args_term = dict() # 要匹配的字段
# args_cate = dict() # 要多字段(两导航)完全匹配
# args_org = dict() # 要多字段(两导航)完全匹配
#
# if keyword:
# query = keyword
# if category:
# args_term["category"] = category
# if org:
# args_org["org"] = org
# if year:
# args_term["year"] = year
# if level:
# args_term["level"] = level
#
# if inid:
# indu_name = Industry.query.filter_by(nid=inid).first().oname
# args_cate["indu"] = indu_name
#
# body = create_body(page, perpage, query, args_term, args_cate, args_org)
#
# try:
# # url = "http://127.0.0.1:9200/policy/_search"
# url = "http://127.0.0.1:9200/typolicy/_search"
# result_es = json.loads(requests.post(url=url, json=body).text)
# print(result_es)
# data = []
# size = result_es["hits"]["total"]
# for item in result_es["hits"]["hits"]:
# data.append({"name": item["_source"]["name"],
# "org": item["_source"]["org"],
# "pubdate": str(item["_source"]["pubdate"]),
# "id": item["_source"]["policyid"]})
# result = {"data": data, "size": size}
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DBERR, msg="数据库查询错误")
#
# return jsonify(code=RET.OK, msg="查询成功", data=result)
# 太原产业政策列表(转mysql)(pc更新)
@api_atlas.route('/industry/policyList', methods=['POST'])
# @login_required
def policy_list():
'''
:return:
'''
req_dict = request.get_json()
inid = req_dict.get("inid") # 行业id
category = req_dict.get("category") # 政策类型
level = req_dict.get("level") # 发布级别
org = req_dict.get("org") # 发布机构
year = req_dict.get("year") # 发布年份
keyword = req_dict.get("keyword") # 搜索园区内容
page = req_dict.get("page") # 分页页码
perpage = req_dict.get("perpage") # 分页大小
if org == "省级":
org = "山西省政府"
if org == "市级":
org = "太原市政府"
if org == "区县":
org = "小店区政府"
if org == "开发区":
org = "山西转型综合改革示范区"
if org == "山西转型综合改革示范区":
org = "山西省转型综合改革示范区"
# 校验参数完整性
if not all([page, perpage]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
try:
indu_policy = InduPolicy.query.order_by(InduPolicy.sorts_level)
# indu_policy = indu_policy.order_by(InduPolicy.sorts_level)
if category:
indu_policy = indu_policy.filter_by(category=category)
if org:
indu_policy = indu_policy.filter(InduPolicy.body.like("%{}%".format(org)))
if year:
indu_policy = indu_policy.filter_by(year=year)
if level:
indu_policy = indu_policy.filter_by(level=level)
if inid:
indu_name = Industry.query.filter_by(nid=inid).first().oname
indu_policy = indu_policy.filter(or_(InduPolicy.navigat.like("%{}%".format(indu_name)),
InduPolicy.navigator.like("%{}%".format(indu_name))))
if keyword: # 如果搜索,全部搜索
indu_policy = InduPolicy.query.filter(InduPolicy.name.like("%{}%".format(keyword)))
else:
indu_policy = indu_policy
size = indu_policy.count()
indu_policy = indu_policy.order_by(InduPolicy.sorts).order_by(InduPolicy.pubdate.desc()).paginate(page,
perpage).items
data = [{"id": i.id,
"name": i.name,
"org": i.org,
"pubdate": str(i.pubdate)[:10]} for i in indu_policy]
result = {"data": data, "size": size}
return jsonify(code=RET.OK, msg="查询成功", data=result)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
# # 产业政策详情(转es)
# @api_atlas.route('/indupolicy/detail', methods=['POST'])
# # @login_required
# def policy_detail():
# '''
# 产业政策详情(从es数据查询文件本地的路径)
# :return:
# '''
# req_dict = request.get_json()
# _id = req_dict.get("id") # 产业政策policyid
# # 校验参数完整性
# if not all([_id]):
# return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")
# body = {"query":
# {"bool": {"must": [{"term": {"policyid": "{}".format(_id)}}],
# "must_not": [],
# "should": []}},
# "from": 0,
# "size": 50,
# "sort": [],
# "aggs": {},
# "_source": [
# "name", "org", "pubdate", "industry", "category",
# "district", "url", "file"
# ],
# }
# try:
# url = "http://127.0.0.1:9200/typolicy/_search"
# result_es = json.loads(requests.post(url=url, json=body).text)
# data = result_es["hits"]["hits"][0]["_source"]
# # 转换https
# # data["file"] = str(data["file"]).replace("http","https")
# return jsonify(code=RET.OK, msg="查询成功", data=data)
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
''''''
# 政策详情
@api_atlas.route("/indupolicy/detail", methods=["POST"])
def policy_detail():
req_dic = request.get_json()
_id = req_dic.get("id")
if not _id:
return jsonify(code=RET.PARAMERR, msg="参数不全")
if _id == 129:
_id = 52
try:
policy = InduPolicy.query.get(_id)
data = {"name": policy.name,
"file": policy.file if policy.file else "-",
"category": policy.category if policy.category else "-",
"org": policy.org if policy.org else "-",
"industry": policy.industry if policy.industry else "-",
"district": policy.district if policy.district else "-",
"pubdate": str(policy.pubdate)[0:10] if policy.pubdate else "-",
"url": policy.url if policy.pubdate else "-",
"post_num": policy.post_num if policy.post_num else ""}
return jsonify(code=RET.OK, msg="查找成功", data=data)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
import json
import requests
from flask import g, current_app, request, jsonify, session
from apps.atlas import api_atlas
from apps.util import login_required
from apps.utils.response_code import RET
from apps.utils.neo4j_conn import conn_neo4j
graph = conn_neo4j()
def deleteDuplicate(li):
'''
列表[字典]去重
:param li:
:return:
'''
temp_list = list(set([str(i) for i in li]))
li = [eval(i) for i in temp_list]
return li
def check(name):
'''
判断当前企业是否有上下游关系,True有、False无
:param name: 节点名
:return:
'''
Cypher = "match (n)-[r]->(m) WHERE m.name='{}' or n.name='{}' return r.type".format(name, name)
res = graph.run(Cypher).data()
res = list(set([i["r.type"] for i in res]))
if res.__contains__("上游行业") or res.__contains__("下游行业"):
return True
return False
# 根据企业查询产品
def body_by_companyName(company_name):
'''
:param company_name: 公司名
:return:
'''
body = {
"query": {
"bool": {
"must": [
{
"match": {
"company_name": "{}".format(company_name)
}
}
],
"must_not": [],
"should": []
}
},
"sort": [],
"aggs": {},
"_source": ["product"]
}
return body
# 根据产品查询企业
def body_by_products(product):
'''
:param company_name: 公司名
:return:
'''
body = {
"query": {
"bool": {
"must": [
{
"match": {
"product": "{}".format(product)
}
}
],
"must_not": [],
"should": []
}
},
"from": 0,
"size": 20, # 限制条数
"sort": [],
"aggs": {},
"_source": ["company_name", "lng", "lat"]
}
return body
def trans_formet(name, list_data):
'''
:param name: str 要转换的主题name
:param list_data: list 要转换的数据列表
:return:
'''
for i in range(len(list_data)):
if list_data[i]["bname"] != name:
if list_data[i]["r.type"] == "上游行业":
list_data[i] = {
"source": name,
"relation": "下游行业",
"target": "{}".format(
list_data[i]["bname"])}
elif list_data[i]["r.type"] == "下游行业":
list_data[i] = {
"source": name,
"relation": "上游行业",
"target": "{}".format(
list_data[i]["bname"])}
else:
list_data[i] = {"source": "{}".format(list_data[i]["bname"]),
"relation": "{}".format(list_data[i]["r.type"]),
"target": "{}".format(list_data[i]["sname"])}
return list_data
def findCenterProducts(name):
'''
查找中间产品
查询当前产品往上直到有上下游关系,并返回产品实体名称和关系名称的列表
:param name: 产品名
:return:
'''
if check(name): # 直接关联上下游
res = [name]
return res
else:
sql = "match (n)-[r]->(m) WHERE m.name='{}' return n.name,r.type".format(name)
# print(sql)
res = graph.run(sql).data()
final_result = [] # 最终产品集
for i in res:
if check(i["n.name"]): # 判断是否有上下游关系(添加到最终产品集)
final_result.append(i["n.name"])
else:
result = findCenterProducts(i["n.name"])
final_result.extend(result)
if len(final_result) >= 1:
return final_result
else:
return []
def offer_company(name):
'''
# 判断是否有供应商
:param name: 产品实体
:return:
'''
try:
url = "http://127.0.0.1:9200/tychain/_search" # 产品对企业
# 1、根据公司查询产品
body = body_by_products(name)
result_es = json.loads(requests.post(url=url, json=body).text)
if result_es["hits"]["total"] >= 1:
return True
return False
except Exception as e:
current_app.logger.error(e)
return False
def findUpDownCompany(name_query, name): # 对中间产品进行上下游产品查询
'''
:param name_query: 要查询的产品
:param name: 中间产品
:return:
'''
sql_all = "match (n) -[r:`下游行业`]->(m) WHERE n.name='{}' return n.name as bname,r.type,m.name as sname UNION " \
"match (n) -[r:`上游行业`]->(m) WHERE m.name='{}' return n.name as bname,r.type,m.name as sname UNION " \
"match (n) -[r:`上游行业`]->(m) WHERE n.name='{}' return n.name as bname,r.type,m.name as sname UNION " \
"match (n) -[r:`下游行业`]->(m) WHERE m.name='{}' return n.name as bname,r.type,m.name as sname ".format(
name, name, name, name)
res_product = graph.run(sql_all).data()
res_product = trans_formet(name, res_product)
nodes = []
links = []
# nodes.append({"id": "{}".format(item), "name": "{}↓".format(item), "category": "2"})
# links.append({"from": "a", "to": "{}".format(item), "text": "产品"})
for i in res_product:
if offer_company(i["target"]): # 判断是否有供应商
nodes.append({"id": "{}".format(i["target"]), "name": "{}↓".format(i["target"]), "category": "3"})
links.append(
{"from": "{}".format(name_query), "to": "{}".format(i["target"]), "text": "{}".format(i["relation"])})
# if i["relation"] == "上游行业":
# if i["source"] == name_query:
# nodes.append({"name": "{}↓".format(i["target"]), "category": 3, "name_query": "{}".format(i["target"]), "isclick": 0})
# links.append({"source": "{}↓".format(i["source"]), "target": "{}↓".format(i["target"]), "name": "{}".format(i["relation"])})
# else:
# nodes.append({"name": "{}↓".format(i["target"]), "category": 3, "name_query": "{}".format(i["target"]), "isclick": 0})
# links.append({"source": "{}↓".format(name_query), "target": "{}↓".format( i["target"]), "name": "{}".format(i["relation"])})
# elif i["relation"] == "下游行业":
# nodes.append({"id": "{}".format(i["target"]), "name": "{}↓".format(i["target"]), "category": "3"})
# links.append({"from": "{}".format(name_query), "to": "{}".format(i["target"]),"text": "{}".format(i["relation"])})
# if i["source"] == name_query:
# nodes.append({"name": "{}↓".format(i["target"]), "category": 4, "name_query": "{}".format(i["target"]), "isclick": 0})
# links.append({"source": "{}↓".format(i["source"]), "target": "{}↓".format(i["target"]), "name": "{}".format(i["relation"])})
# else:
# nodes.append({"name": "{}↓".format(i["target"]), "category": 4, "name_query": "{}".format(i["target"]), "isclick": 0})
# links.append({"source": "{}↓".format(name_query), "target": "{}↓".format(i["target"]), "name": "{}".format(i["relation"])})
else:
nodes.append({"id": "{}".format(i["target"]), "name": "{}".format(i["target"]), "category": "3"})
links.append(
{"from": "{}".format(name_query), "to": "{}".format(i["target"]), "text": "{}".format(i["relation"])})
# if i["relation"] == "上游行业":
# if i["source"] == name_query:
# nodes.append({"name": "{}".format(i["target"]), "category": 3, "name_query": "{}".format(i["target"]), "isclick": 0})
# links.append({"source": "{}↓".format(i["source"]), "target": "{}".format(i["target"]), "name": "{}".format(i["relation"])})
# else:
# nodes.append({"name": "{}".format(i["target"]), "category": 3, "name_query": "{}".format(i["target"]), "isclick": 0})
# links.append({"source": "{}↓".format(name_query), "target": "{}".format(i["target"]), "name": "{}".format(i["relation"])})
# elif i["relation"] == "下游行业":
# if i["source"] == name_query:
# nodes.append({"name": "{}".format(i["target"]), "category": 4, "name_query": "{}".format(i["target"]), "isclick": 0})
# links.append({"source": "{}↓".format(i["source"]), "target": "{}".format(i["target"]), "name": "{}".format(i["relation"])})
# else:
# nodes.append({"name": "{}".format(i["target"]), "category": 4, "name_query": "{}".format(i["target"]), "isclick": 0})
# links.append({"source": "{}↓".format(name_query), "target": "{}".format(i["target"]), "name": "{}".format(i["relation"])})
return nodes, links
def findUDP(name): # 对中间产品进行上下游产品查询
'''
:param name_query: 要查询的产品
:param name: 中间产品
:return:
'''
sql_all = "match (n) -[r:`下游行业`]->(m) WHERE n.name='{}' return n.name as bname,r.type,m.name as sname UNION " \
"match (n) -[r:`上游行业`]->(m) WHERE m.name='{}' return n.name as bname,r.type,m.name as sname UNION " \
"match (n) -[r:`上游行业`]->(m) WHERE n.name='{}' return n.name as bname,r.type,m.name as sname UNION " \
"match (n) -[r:`下游行业`]->(m) WHERE m.name='{}' return n.name as bname,r.type,m.name as sname ".format(
name, name, name, name)
res_product = graph.run(sql_all).data()
res_product = trans_formet(name, res_product)
products = list()
for i in res_product:
products.append(i["target"])
return products
@api_atlas.route("/find_zero", methods=['POST'])
def find_zero():
try:
get_data = request.get_json()
name = get_data.get('company_name')
result = {
"nodes": [{"id": "a", "name": "{}↓".format(name), "category": "1"}],
"links": [],
"rootId": 'a'
}
return jsonify(code=RET.OK, msg="获取成功", data=result)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据异常", data={})
@api_atlas.route("/find_next", methods=['POST'])
def find_next():
req_dict = request.get_json()
name = req_dict.get('name') # 名称
# id = req_dict.get("id") # id
category = req_dict.get("category")
# 检查参数的完整性
if not all([name, category]):
return jsonify(code=RET.DATAERR, msg="参数不完整")
try:
if category == "1": # 查询企业的产品
url = "http://localhost:9200/ty_com2product/_search" # 产品对企业
# 1、根据公司查询产品
body = body_by_companyName(name)
result_es = json.loads(requests.post(url=url, json=body).text)
res = list(set([i["_source"]["product"] for i in result_es["hits"]["hits"]]))
if res:
nodes = list()
links = list()
result = dict()
products = list(set(res))
for item in products:
nodes.append({"id": "{}".format(item), "name": "{}↓".format(item), "category": "2"})
links.append({"from": "a", "to": "{}".format(item), "text": "产品"})
result["nodes"] = nodes
result["links"] = links
return jsonify(code=RET.OK, msg="获取成功", data=result)
else:
return jsonify(code=RET.NODATA, msg="无数据", data={})
elif category == "2": # 根据产品查询上下游产品
nodes = list()
links = list()
center_product = findCenterProducts(name) # 获取中间产品
for udp in center_product:
# findUpDownCompany(udp) # 获取上下游行业
antity, relation = findUpDownCompany(name, udp) # 获取上下游行业
nodes.extend(antity)
links.extend(relation)
nodes = deleteDuplicate(nodes)
links = deleteDuplicate(links)
result = {
"nodes": nodes,
"links": links
}
return jsonify(code=RET.OK, msg="获取成功", data=result)
elif category == "3": # 产品查询供应商
url = "http://localhost:9200/ty_com2product/_search"
body = body_by_products(name)
companys_return = json.loads(requests.post(url=url, json=body).text)
res = [i["_source"]["company_name"] for i in companys_return["hits"]["hits"]]
if res:
nodes = list()
links = list()
result = dict()
products = list(set(res))
for item in products:
nodes.append({"id": "{}".format(item), "name": "{}".format(item), "category": "4"})
links.append({"from": "{}".format(name), "to": "{}".format(item), "text": "{}".format("供应商企业")})
result["nodes"] = nodes
result["links"] = links
return jsonify(code=RET.OK, msg="获取成功", data=result)
else:
return jsonify(code=RET.NODATA, msg="无数据")
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据异常", data={})
# 企业供应链地图
@api_atlas.route("/get_semic_map", methods=['POST'])
def get_semic_map():
try:
res = request.get_json()
company_name = res.get('company_name').strip()
c_type = res.get('c_type')
url = "http://localhost:9200/ty_com2product/_search" # 产品对企业
# 1、根据公司查询产品
body = body_by_companyName(company_name)
result_es = json.loads(requests.post(url=url, json=body).text)
products = list(set([i["_source"]["product"] for i in result_es["hits"]["hits"]])) # 无需去重,最终数据不会出现重复项
# print("直接产品:", products)
# 2、查询上下游产品
products_center = list()
for i in products:
products_center.extend(findCenterProducts(i))
products_uad = list()
for j in products_center:
products_uad.extend(findUDP(j))
products_uad = list(set(products_uad))
# print("中间产品:", products_uad)
# 3、根据产品进行供应商及其经纬度查询
companys = list()
for pro in products_uad:
body = body_by_products(pro)
companys_return = json.loads(requests.post(url=url, json=body).text)
companys.extend([i["_source"] for i in companys_return["hits"]["hits"]])
data = list()
if companys:
for item in companys:
data.append({"name": item["company_name"],
"jwd": {"lng": item["lng"], # 园区地址出的经纬度
"lat": item["lat"]}
})
return jsonify(code=RET.OK, msg="获取成功", data=data)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.PARAMERR, msg="参数错误")
from flask import current_app, request, jsonify
from apps.atlas import api_atlas
from apps.util import login_required
from apps.utils.response_code import RET
from apps.models import *
from apps.utils.neo4j_conn import conn_neo4j, neo4j_dict
from apps import redis_store
import json
graph = conn_neo4j()
'''行业名转换ptp字典两个 neo4j_dict line 164/177'''
def deleteDuplicate(li):
'''列表[字典]去重'''
temp_list = list(set([str(i) for i in li]))
li = [eval(i) for i in temp_list]
return li
def find_up_thr(name_query, relation):
if relation == "中游行业":
relation_c = "下位产品"
else:
relation_c = relation
# 零级,上中下三游
data = {
"node": "{}".format(relation[:2]),
"level": 1,
"subNodeList": [],
}
sql_01 = "match (n) -[r:`{}`]->(m) WHERE n.name='{}' return n.name,r.type,m.name".format(relation_c, name_query)
res_zero = graph.run(sql_01).data()
res_one = list(set([i["m.name"] for i in list(res_zero)])) # 不重复的一级节点
for it in res_one: # 一级节点
pname_one = it
# 一级
node_one = {
"node": "{}".format(pname_one),
"level": 2,
"subNodeList": []
}
sql_02 = "match (n) -[r]->(m) WHERE n.name='{}' return n.name,r.type,m.name".format(pname_one)
result = graph.run(sql_02).data()
result = list(set([i["m.name"] for i in list(result)])) # 不重复的二级节点
for item in result:
pname_two = item
# 二级
node_two = {
"node": "{}".format(pname_two),
"level": 3,
"subNodeList": []
}
sql_03 = "match (n) -[r]->(m) WHERE n.name='{}' return n.name,r.type,m.name".format(pname_two)
result3 = graph.run(sql_03).data()
result3 = list(set([i["m.name"] for i in list(result3)])) # 不重复的三级节点
for itm in result3:
pname_thr = itm
# 三级
node_thr = {
"node": "{}".format(pname_thr),
"level": 4,
"subNodeList": []
}
node_two["subNodeList"].append(node_thr)
node_one["subNodeList"].append(node_two)
data["subNodeList"].append(node_one)
return data
# 获取产业集群名称
@api_atlas.route('/industry/cluster', methods=['GET'])
def get_cluster():
try:
cluster_obj = Industry.query.filter_by(fid=0).all()
data = {
"cluster": [
{"id": i.nid, 'industry_level': 1, 'name': i.name,
"subNodeList": [{'id': j.nid, 'industry_level': 2, "name": j.name} for j in
Industry.query.filter_by(fid=i.nid)]} for i in
cluster_obj]
}
return jsonify(code=RET.OK, msg='产业集群名称获取成功!', data=data)
except Exception as e:
current_app.logger.error(e)
# 行业产品公司数量(链图,根据地理位置)
@api_atlas.route('/industry/chain', methods=['POST'])
# @login_required
def industry_chain():
'''
行业id->行业链标题-》上中下游-》查询数值
:return:
'''
req_dict = request.get_json()
inid = req_dict.get("inid") # 二级行业id(二级行业显示链图)
# district = req_dict.get("district") # 区县
# 校验参数完整性
if not all([inid]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
try:
# name_query = "jc" + str(inid) + str(district)
# if redis_store.get(name_query) is not None:
# data = json.loads(redis_store.get(name_query))
# return jsonify(code=RET.OK, msg="获取成功", data=data)
# 行业使用名
industryName = Industry.query.filter_by(nid=inid).first().oname
ptp = neo4j_dict()
if industryName in ptp:
industryName = ptp[industryName]
# print(industryName)
result = {
"industryChain": industryName,
"nodeList": [find_up_thr(industryName, "上游行业"),
find_up_thr(industryName, "中游行业"),
find_up_thr(industryName, "下游行业")]
}
# redis缓存
# redis_store.set(name_query, json.dumps(result))
# redis_store.expire(name_query, 30 * 24 * 3600)
# print("redis")
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据异常")
return jsonify(code=RET.OK, msg="获取成功", data=result)
# 点击产业联动显示企业
@api_atlas.route('/industry/enterprise', methods=['POST'])
# @login_required
def industry_enterprise():
'''骨干企业数据'''
req_dict = request.get_json()
inid = req_dict.get("inid") # 行业id
industry_level = req_dict.get("industry_level") # 行业等级,(父行个为"1",子行业为"2")
product = req_dict.get("product")
page = req_dict.get("page") # 分页页码
perpage = req_dict.get("perpage") # 分页大小
# sorts = req_dict.get("sorts") # 排序 sorts "1"按时间降序 ,“2”按热度降序
# 校验参数完整性
if not all([industry_level, page, perpage]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
try:
if industry_level == 1:
company = Company.query.filter_by(f_type=inid, city="晋城市")
else:
company = Company.query.filter_by(c_type=inid, city="晋城市")
if product:
company = Company.query.filter(Company.product_all.like("%{}%".format(product)))
size = company.count()
companys = company.order_by(Company.hots.desc()).paginate(page, perpage).items # 企业热度倒序
df = [{"id": i.id,
"company_name": i.company_name,
"district": i.district,
"build_date": (i.build_date).strftime("%Y-%m-%d %H:%M:%S"),
"legal": i.legal,
"capital_nums": i.capital_nums,
"entype": i.entype,
"address": i.address,
"telephone": i.telephone,
"high_new": '高新技术企业' if i.high_new == '1' else '',
"tbe": '科技型中小企业' if i.tbe == '1' else '',
"quoted_company": '上市企业' if i.quoted_company == '1' else '',
"zjtg": '精专特新企业' if i.zjtg == '1' else '',
"unicorn": '独角兽企业' if i.unicorn == '1' else '',
"dengl": '瞪羚企业' if i.dengl == '1' else '',
"isfive": '五百强企业' if i.isfive == '1' else '',
"scale": '规模以上企业' if i.scale == '1' else ''
} for i in companys]
data = {"size": size, "df": df}
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
return jsonify(code=RET.OK, msg="获取成功", data=data)
# 点击产业创新资源联动显示 innovation resource
@api_atlas.route('/innovate/resource', methods=['POST'])
def industry_resource():
'''创新资源机构列表'''
req_dict = request.get_json()
inid = req_dict.get("inid") # 行业id
industry_level = req_dict.get("industry_level") # 行业等级,(父行业高端设备等五个为"1",子行业为"2")
select_flag = req_dict.get("select_flag") # 机构类型id. 高等院校1,科研机构2,创新平台3,产业服务平台4
page = req_dict.get("page") # 分页页码
perpage = req_dict.get("perpage") # 分页大小
# 校验参数完整性
if not all([inid, industry_level, select_flag, page, perpage]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
name = Industry.query.filter_by(nid=inid).first().oname
if select_flag == 1: # 高等院校
try:
if industry_level == 1:
college = College.query.filter(College.navigator.like("%{}%".format(name)))
else:
college = College.query.filter(College.navigat.like("%{}%".format(name)))
size = college.count()
college = college.paginate(page, perpage).items
data = {"df": [{"id": i.id,
"name": i.name,
"admin": i.admin,
"buildate": i.buildate,
"charge": i.charge,
"cate": i.category,
"nature": i.nature,
"ccode": i.ccode,
"address": i.address,
} for i in college],
"size": size}
return jsonify(code=RET.OK, msg="查询成功", data=data)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DATAERR, msg="参数错误")
elif select_flag == 2: # 科研机构
if industry_level == 1:
scientific = Scientific.query.filter(Scientific.navigator.like("%{}%".format(name)))
else:
scientific = Scientific.query.filter(Scientific.navigat.like("%{}%".format(name)))
size = scientific.count()
scientific = scientific.paginate(page, perpage).items
data = {"df": [{"id": i.id,
"name": i.name,
"admin": i.admin,
"telephone": i.telephone,
"fax": i.fax,
"postcode": i.postcode,
"address": i.address} for i in scientific],
"size": size}
return jsonify(code=RET.OK, msg="查询成功", data=data)
elif select_flag == 3: # 创新平台3
if industry_level == 1:
lab = Lab.query.filter(Lab.navigator.like("%{}%".format(name)))
else:
lab = Lab.query.filter(Lab.navigat.like("%{}%".format(name)))
size = lab.count()
lab = lab.paginate(page, perpage).items
data = {"df": [{"id": i.id,
"name": i.name,
"admin": i.admin,
"cate": i.cate,
"fax": i.fax,
"postcode": i.postcode,
"address": i.address} for i in lab],
"size": size}
return jsonify(code=RET.OK, msg="查询成功", data=data)
else:
return jsonify(code=RET.PARAMERR, msg="参数错误")
def get_data(name, industry_level, select_flag, page, perpage):
try:
if select_flag in [1, 2]: # 当选择行政区/园区时
if select_flag == 1 and industry_level == 1: # 当选择的是父产业的行政区时
induzone = Induzone.query.filter(Induzone.cate.like('行政区'), Induzone.navigator.like("%{}%".format(name)))
elif select_flag == 1 and industry_level == 2: # 当选择的是子产业的行政区时
induzone = Induzone.query.filter(Induzone.cate.like('行政区'), Induzone.navigat.like("%{}%".format(name)))
elif select_flag == 2 and industry_level == 1: # 当选择的是父产业的园区时
induzone = Induzone.query.filter(Induzone.cate.like('产业园区'), Induzone.navigator.like("%{}%".format(name)))
elif select_flag == 2 and industry_level == 2: # 当选择的是父产业的园区时
induzone = Induzone.query.filter(Induzone.cate.like('产业园区'), Induzone.navigat.like("%{}%".format(name)))
size = induzone.count() # 分页总数
induzone = induzone.paginate(page, perpage).items
if select_flag == 1:
# 封装行政区数据
admin_data = {"admin_data": [{
"id": i.id,
"image": i.image,
# "region": i.region,
"region": i.district,
"cate": i.cate, # 园区类型
"area": i.area,
"address": i.address,
"cluster": i.cluster} for i in induzone],
"size": size}
return admin_data
if select_flag == 2:
# 封装园区数据
garden_data = {"garden": [{"id": i.id,
"name": i.name, # 园区名称
"region": i.region, # 所属地区
"phone": i.phone, # 联系电话
"level": i.level, # 园区级别
"cate": i.cate, # 园区类型
"address": i.address, } for i in induzone], # 园区地址
"size": size}
return garden_data
if select_flag == 3: # 当选择载体土地时
if industry_level == 1: # 当选择的是父产业时
land = ZaitiLand.query.filter(ZaitiLand.navigator.like("%{}%".format(name)))
else:
land = ZaitiLand.query.filter(ZaitiLand.navigat.like("%{}%".format(name)))
size = land.count() # 分页总数
land = land.paginate(page, perpage).items
# 封装土地数据
land_data = {"land_data": [{
"id": i.id,
"name": i.name,
"num": i.num,
"nature": i.nature,
"acreage": i.acreage,
"industry_type": i.industry_type,
"telephone": i.telephone
} for i in land], "size": size}
return land_data
if select_flag == 4: # 当选择载体楼宇时
if industry_level == 1: # 当选择的是父产业时
build = ZaitiBuild.query.filter(ZaitiBuild.navigator.like("%{}%".format(name)))
else:
build = ZaitiBuild.query.filter(ZaitiBuild.navigat.like("%{}%".format(name)))
size = build.count() # 分页总数
build = build.paginate(page, perpage).items
# 封装楼宇数据
build_data = {
"build_data": [{
"id": i.id,
"name": i.name,
"acreage": i.acreage,
"buide_type": i.buide_type,
"industry_type": i.industry_type,
"telephone": i.telephone,
"addr": i.addr,
} for i in build], "size": size
}
return build_data
if select_flag == 5: # 当选择载体厂房时
if industry_level == 1: # 当选择的是父产业时
factory = ZaitiFactory.query.filter(ZaitiFactory.navigator.like("%{}%".format(name)))
else:
factory = ZaitiFactory.query.filter(ZaitiFactory.navigat.like("%{}%".format(name)))
size = factory.count() # 分页总数
factory = factory.paginate(page, perpage).items
# 封装楼宇数据
factory_data = {
"factory_data": [{
"id": i.id,
"name": i.name,
"acreage": i.acreage,
"factory_type": i.factory_type,
"industry_type": i.industry_type,
"telephone": i.telephone,
"addr": i.addr,
} for i in factory], "size": size
}
return factory_data
except Exception as e:
print(e)
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
# 产业载体
@api_atlas.route('/carrier/zaiti', methods=['POST'])
def industry_zaiti():
'''产业载体数据'''
req_dict = request.get_json()
inid = req_dict.get("inid") # 行业id
industry_level = req_dict.get("industry_level") # 行业等级,(父行业高端设备等五个为"1",子行业为"2")
select_flag = req_dict.get("select_flag") # 1为行政区,2为园区,3为产业载体,4为土地,5为楼宇,6为厂房
page = req_dict.get("page") # 分页页码
perpage = req_dict.get("perpage") # 分页大小
# 校验参数完整性
if not all([page, perpage]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
# if inid:
name = Industry.query.filter_by(nid=inid).first().oname # 获取导航对应的真名
try:
data = get_data(name, industry_level, select_flag, page, perpage)
return jsonify(code=RET.OK, msg="数据查询成功", data=data)
except Exception as e:
current_app.logger.error(e)
# 产业政策
@api_atlas.route('/industry/indus_policy', methods=['POST'])
def industry_policy():
"""产业政策数据"""
req_dict = request.get_json()
inid = req_dict.get("inid") # 行业id
industry_level = req_dict.get("industry_level") # 行业等级,(父行业高端设备等五个为"1",子行业为"2")
page = req_dict.get("page") # 分页页码
perpage = req_dict.get("perpage") # 分页大小
# 校验参数完整性
if not all([page, perpage]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
try:
indu_policy = ''
size = ''
name = Industry.query.filter_by(nid=inid).first().oname # 获取导航对应的真名
if industry_level == 1:
indu_policy = InduPolicy.query.filter(InduPolicy.navigator.like("%{}%".format(name)))
size = indu_policy.count() # 分页总数
indu_policy = indu_policy.paginate(page, perpage).items
if industry_level == 2:
indu_policy = InduPolicy.query.filter(InduPolicy.navigat.like("%{}%".format(name)))
size = indu_policy.count() # 分页总数
indu_policy = indu_policy.paginate(page, perpage).items
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
# 封装政策数据
policy_data = {
"policy_data": [{
"id": i.id,
"name": i.name,
"org": i.org,
"pubdate": (i.pubdate).strftime("%Y-%m-%d %H:%M:%S")
} for i in indu_policy],
"size": size
}
return jsonify(code=RET.OK, msg="政策数据查询成功", data=policy_data)
# 产业政策详情信息-复用招商驾驶舱政策详情接口
# 骨干企业详情信息
# 创新资源-高等院校详情
@api_atlas.route('/innovate/college_detail', methods=['POST'])
def get_college_detail():
req_dict = request.get_json()
college_id = req_dict.get('id')
try:
college = College.query.filter_by(id=college_id).first()
# 封装院校数据
data = {
"name": college.name, # 校名
"charge": college.charge, # 主管部门
"buildate": college.buildate, # 创办时间
"nature": college.nature, # 办学性质
"clas": college.clas, # 学校类别
"address": college.address, # 校址
"introduct": college.introduct, # 简介
"ccode": college.ccode, # 学校代码
"feature": college.feature, # 学校特色
"research": college.research, # 研究方向
"major": college.major,
"faculty": college.faculty,
"lng": college.lng, # 经度
"lat": college.lat # 纬度
}
return jsonify(code=RET.OK, msg='院校详情查询成功!', data=data)
except Exception as e:
current_app.logger.error(e)
# 创新资源-科研机构详情
@api_atlas.route('/innovate/scientific_detail', methods=['POST'])
def get_scientific_detail():
req_dict = request.get_json()
scientific_id = req_dict.get('id')
try:
scientific = Scientific.query.filter_by(id=scientific_id).first()
# 封装科研机构数据
data = {
"name": scientific.name, # 名称
"admin": scientific.admin, # 行政区
"telephone": scientific.telephone, # 联系电话
"fax": scientific.fax, # 传真
"postcode": scientific.postcode, # 邮编
"address": scientific.address, # 地址
"introduct": scientific.introduct, # 简介
"lng": scientific.lng, # 经度
"lat": scientific.lat # 纬度
}
return jsonify(code=RET.OK, msg='科研机构详情查询成功!', data=data)
except Exception as e:
current_app.logger.error(e)
# 创新资源-创新平台详情
@api_atlas.route('/innovate/Lab_detail', methods=['POST'])
def get_lab_detail():
req_dict = request.get_json()
lab_id = req_dict.get('id')
try:
lab = Lab.query.filter_by(id=lab_id).first()
# 封装创新平台数据
data = {
"name": lab.name, # 名称
"address": lab.address, # 地址
"introduct": lab.introduct, # 简介
"lng": lab.lng, # 经度
"lat": lab.lat # 纬度
}
return jsonify(code=RET.OK, msg='创新平台详情查询成功!', data=data)
except Exception as e:
current_app.logger.error(e)
# 产业载体-各类型详情信息
@api_atlas.route('/carrier/zaiti_detail', methods=['POST'])
def get_zaiti_detail_data():
req_dict = request.get_json()
id = req_dict.get('id')
cate_id = req_dict.get('cate_id') # 1为行政区,2为园区,3为土地,4为楼宇,5为厂房
print(cate_id)
if cate_id in [1, 2]:
try:
induzone = Induzone.query.filter_by(id=id).first()
data = {
"district": induzone.district,
"cate": induzone.cate,
"area": induzone.area,
"address": induzone.address,
"cluster": induzone.cluster,
"name": induzone.name, # 名称
# "district": induzone.district, # 所属地区
"phone": induzone.phone, # 电话
"email": induzone.email,
# "address": induzone.address, # 园区地址
"industry_position": induzone.industry_position, # 产业定位
# "cate": induzone.cate, # 园区类型
"gdp": induzone.gdp, # GDP
"represent": induzone.represent, # 代表企业
"introduct": induzone.introduct, # 简介
"level": induzone.level, # 等级
"charge": induzone.charge, # 园区负责人
"site": induzone.site, # 园区所在地
"industry_type": induzone.industry_type, # 产业类型
# "area": induzone.area, # 面积
"out_power": induzone.out_power, # 产出强度(万元/亩)
"invest_power": induzone.invest_power, # 亩均投资强度(万元/亩)
"value_product": induzone.value_product, # 亩均年产值(万元/亩)
"tax": induzone.tax, # 亩均年税收(万元/亩)
"indu_land": induzone.indu_land, # 工业土地均价(万元/亩)
"comm_land": induzone.comm_land, # 商办土地均价(万元/亩)
"highmag": induzone.highmag, # 高层管理人员(元/月)
"middlemag": induzone.middlemag, # 中级管理人员(元/月)
"worker": induzone.worker, # 普通员工(元/月)
"trans_facility": induzone.trans_facility, # 交通配套
"goods_trans": induzone.goods_trans, # 货物运输
"live_facility": induzone.live_facility, # 园区生活配套
"market": induzone.market, # 百货商场
"hotel_bus": induzone.hotel_bus, # 酒店商务
"medical": induzone.medical, # 医疗机构
"education": induzone.education, # 教育教育
}
return jsonify(code=RET.OK, msg='详情数据查询成功!', data=data)
except Exception as e:
current_app.logger.error(e)
if cate_id == 3:
try:
land = ZaitiLand.query.filter_by(id=id).first()
data = {
"num": land.num, # 编号
"name": land.name, # 地块名称
"addr": land.addr, # 地址
"nature": land.nature, # 土地性质
"acreage": land.acreage, # 面积
"target": land.target, # 规划指标
"age_limit": land.age_limit, # 出让年限
"industry_type": land.industry_type, # 产业类型
"telephone": land.telephone # 电话
}
return jsonify(code=RET.OK, msg='土地详情查询成功!', data=data)
except Exception as e:
current_app.logger.error(e)
if cate_id == 4:
try:
build = ZaitiBuild.query.filter_by(id=id).first()
data = {
"name": build.name, # 楼宇名称
"addr": build.addr, # 地址
"acreage": build.acreage, # 面积
"buide_type": build.buide_type, # 楼宇类型
"industry_type": build.industry_type, # 产业类型
"rate": build.rate, # 出租率
"telephone": build.telephone # 电话
}
return jsonify(code=RET.OK, msg='楼宇详情查询成功!', data=data)
except Exception as e:
current_app.logger.error(e)
if cate_id == 5:
try:
factory = ZaitiFactory.query.filter_by(id=id).first()
data = {
"name": factory.name, # 厂房名称
"addr": factory.addr, # 地址
"acreage": factory.acreage, # 面积
"structure": factory.structure, # 简介
"height": factory.height, # 高度
"bearing": factory.bearing, # 承重
"new_level": factory.new_level, # 新旧程度
"other": factory.other, # 其他
"industry_type": factory.industry_type, # 产业类型
"factory_type": factory.factory_type, # 厂房类型
"telephone": factory.telephone, # 电话
}
return jsonify(code=RET.OK, msg='厂房详情查询成功!', data=data)
except Exception as e:
current_app.logger.error(e)
from flask import Blueprint
# 创建蓝图对象
api_map = Blueprint("api_map", __name__)
from . import view
'''招商地图页'''
from flask import g, current_app, request, jsonify, session
from apps.attract import api_map
from apps.util import login_required, verify_token
from apps.utils.response_code import RET
from apps.models import *
from apps.utils.neo4j_conn import conn_neo4j, neo4j_dict
import json
import requests
from apps import db, constants, redis_store
'''本页接口使用全国企业库enterprise'''
graph = conn_neo4j()
# 颜色计数
def jishu(num):
if num >= 0 and num <= 50:
return "#72D4F1"
if num > 50 and num <= 100:
return "#00BAF6"
if num > 100 and num <= 200:
return "#4F9FFF"
if num > 200 and num <= 500:
return "#4265F6"
if num > 500 and num <= 1000:
return "#0052d6"
if num > 1000:
return "#0245AE"
# 招商地图下的色块图(同右侧得数量分布饼图)
@api_map.route('/AttractMap', methods=['POST'])
# @login_required
def attract_map():
'''招商地图'''
req_dict = request.get_json()
inid = req_dict.get("inid") # 行业id
province = req_dict.get("province")
city = req_dict.get("city")
district = req_dict.get("district")
product = req_dict.get("product") # 产业产品选择
try:
enterprise = Enterprise.query.filter_by(c_type=inid)
if product:
enterprise = enterprise.filter(Enterprise.product_all.like("%{}%".format(product)))
# print(enterprise)
df = list()
if not province: # 全国,省数据
provinces = Enterprise.query.with_entities(Enterprise.province).distinct().all()
provinces = [i[0] for i in provinces if i[0]] # 拿到省份的无重复值
for pro in provinces:
num = enterprise.filter_by(province=pro).count()
province_data = Enterprise.query.filter_by(province=pro).first()
df.append({"name": pro,
"value": num,
"color": jishu(num),
"jwd": {"lng": province_data.p_lng, "lat": province_data.p_lat}})
return jsonify(code=RET.OK, msg="获取成功", data=df)
if province and not city: # 省-》市数据
cities = Enterprise.query.filter_by(province=province).with_entities(Enterprise.city).distinct().all()
cities = [i[0] for i in cities if i[0]] # 拿到城市的无重复值
for cit in cities:
num = enterprise.filter_by(province=province, city=cit).count()
city_data = Enterprise.query.filter_by(province=province, city=cit).first()
df.append({"name": cit,
"value": num,
"color": jishu(num),
"jwd": {"lng": city_data.c_lng, "lat": city_data.c_lat}})
return jsonify(code=RET.OK, msg="获取成功", data=df)
if province and city and not district: # 市-》区数据
districts = Enterprise.query.filter_by(province=province, city=city).with_entities(
Enterprise.district).distinct().all()
districts = [i[0] for i in districts if i[0]] # 拿到区县的无重复值
for dis in districts:
num = enterprise.filter_by(province=province, city=city, district=dis).count()
district_data = Enterprise.query.filter_by(province=province, city=city, district=dis).first()
df.append({"name": dis,
"value": num,
"color": jishu(num),
"jwd": {"lng": district_data.d_lng, "lat": district_data.d_lat}})
return jsonify(code=RET.OK, msg="获取成功", data=df)
if province and city and district: # 区数据
num = enterprise.filter_by(province=province, city=city, district=district).count()
district_data = Enterprise.query.filter_by(province=province, city=city, district=district).first()
print(district_data)
if district_data:
df.append({"name": district,
"value": num,
"color": "",
"jwd": {"lng": district_data.d_lng, "lat": district_data.d_lat}})
return jsonify(code=RET.OK, msg="获取成功", data=df)
else:
return jsonify(code=RET.OK, msg="无满足条件数据", data=df)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
# 为右侧全国地图企业数据
@api_map.route('/EnterpriseTop5', methods=['POST'])
# @login_required
def attract_cnums():
'''招商地图'''
req_dict = request.get_json()
inid = req_dict.get("inid") # 行业id
province = req_dict.get("province")
city = req_dict.get("city")
district = req_dict.get("district")
product = req_dict.get("product") # 产业产品选择
try:
enterprise = Enterprise.query.filter_by(c_type=inid)
if product:
enterprise = enterprise.filter(Enterprise.product_all.like("%{}%".format(product)))
# print(enterprise)
df = list()
if not province: # 全国,省数据
provinces = Enterprise.query.with_entities(Enterprise.province).distinct().all()
provinces = [i[0] for i in provinces if i[0]] # 拿到省份的无重复值
for pro in provinces:
num = enterprise.filter_by(province=pro).count()
df.append({"name": pro, "value": num})
df = sorted(df, key=lambda x: x["value"], reverse=True)
return jsonify(code=RET.OK, msg="获取成功", data=df[:5])
if province and not city: # 省-》市数据
cities = Enterprise.query.filter_by(province=province).with_entities(Enterprise.city).distinct().all()
cities = [i[0] for i in cities if i[0]] # 拿到城市的无重复值
for cit in cities:
num = enterprise.filter_by(province=province, city=cit).count()
df.append({"name": cit, "value": num})
df = sorted(df, key=lambda x: x["value"], reverse=True)
return jsonify(code=RET.OK, msg="获取成功", data=df[:5])
if province and city and not district: # 市-》区数据
districts = Enterprise.query.filter_by(province=province, city=city).with_entities(
Enterprise.district).distinct().all()
districts = [i[0] for i in districts if i[0]] # 拿到区县的无重复值
for dis in districts:
num = enterprise.filter_by(province=province, city=city, district=dis).count()
df.append({"name": dis, "value": num})
df = sorted(df, key=lambda x: x["value"], reverse=True)
return jsonify(code=RET.OK, msg="获取成功", data=df[:5])
if province and city and district: # 区数据
num = enterprise.filter_by(province=province, city=city, district=district).count()
df.append({"name": district, "value": num})
df = sorted(df, key=lambda x: x["value"], reverse=True)
return jsonify(code=RET.OK, msg="获取成功", data=df[:5])
return jsonify(code=RET.DATAERR, msg="地区参数错误")
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
# 全国企业列表
@api_map.route('/AttractEnterprise', methods=['POST'])
# @login_required
def enterprise():
'''
太原市企业列表
:return:
'''
req_dict = request.get_json()
inid = req_dict.get("inid") # 行业id
page = req_dict.get("page") # 分页页码
perpage = req_dict.get("perpage") # 分页大小
province = req_dict.get("province")
city = req_dict.get("city")
district = req_dict.get("district")
product = req_dict.get("product") # 产业产品选择
if not all([page, perpage]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
try:
if inid: # 子行业分类
enterprise = Enterprise.query.filter_by(c_type=inid)
else:
enterprise = Enterprise.query.filter_by()
# 区域选择
if province:
enterprise = enterprise.filter_by(province=province)
if city:
enterprise = enterprise.filter_by(city=city)
if district:
enterprise = enterprise.filter_by(district=district)
if product:
enterprise = enterprise.filter(Enterprise.product_all.like("%{}%".format(product)))
size = enterprise.count()
enterprise = enterprise.order_by(Enterprise.hots.desc()).paginate(page, perpage).items # 企业热度倒序
df = [{"id": i.id,
"company_name": i.company_name,
"hots": i.hots} for i in enterprise]
data = {"size": size, "df": df}
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
return jsonify(code=RET.OK, msg="获取成功", data=data)
# 招商地图下的散点图(至区后)
@api_map.route('/AttractSdmap', methods=['POST'])
# @login_required
def attract_sdmap():
'''招商地图'''
req_dict = request.get_json()
inid = req_dict.get("inid") # 行业id
province = req_dict.get("province")
city = req_dict.get("city")
district = req_dict.get("district")
product = req_dict.get("product") # 产业产品选择
# 校验参数完整性
if not all([district]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
try:
if inid:
enterprise = Enterprise.query.filter_by(c_type=inid)
else:
enterprise = Enterprise.query.filter_by()
# 企业类型
# if entype:
# enterprise = enterprise.filter_by(entypeid=entype)
# # 企业资质
# if qualificat:
# if qualificat == 1:
# enterprise = enterprise.filter_by(high_new=1)
# if qualificat == 2:
# enterprise = enterprise.filter_by(tbe=1)
# if qualificat == 3:
# enterprise = enterprise.filter_by(quoted_company=1)
# if qualificat == 4:
# enterprise = enterprise.filter_by(isfive=1)
# if qualificat == 5:
# enterprise = enterprise.filter_by(unicorn=1)
# if qualificat == 6:
# enterprise = enterprise.filter_by(dengl=1)
# # 注册资本
# if capital:
# enterprise = enterprise.filter_by(capital_id=capital)
# # 上市板块
# if quoted:
# enterprise = enterprise.filter_by(public_id=quoted)
# 区域选择
if district:
# enterprise = enterprise.filter_by(district=district)
enterprise = enterprise.filter_by(province=province, city=city, district=district)
# 成立时间id
# if yearid:
# enterprise = enterprise.filter_by(yearid=yearid)
# 融资轮次
# if roundid:
# enterprise = enterprise.filter_by(roundid=roundid)
if product:
enterprise = enterprise.filter(Enterprise.product_all.like("%{}%".format(product)))
# enterprise = enterprise.filter_by(province=province, city=city, district=district).all()
enterprise = enterprise.all()
data = []
if enterprise:
for com in enterprise:
data.append({"id": com.id,
"name": com.company_name,
"jwd": {"lng": com.lng, # 企业地址出的经纬度
"lat": com.lat}
}) # 上下中游
else:
return jsonify(code=RET.OK, msg="获取失败,无数据", data=data)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
return jsonify(code=RET.OK, msg="获取成功", data=data)
# # 全国企业条件选择导航(类型,资质,上市,融资)
# @api_map.route('/attract/field', methods=['GET'])
# @login_required
# def field():
# '''太原市企业条件选择导航获取'''
# try:
# property = Property.query.filter_by(statu=1)
#
# typy = property.filter_by(sid=1, statu=1).all()
# qualificat = property.filter_by(sid=2, statu=1).all()
# quoted = property.filter_by(sid=3, statu=1).all()
# financ = property.filter_by(sid=4, statu=1).all()
#
# data = {"entype": [{"label": i.name, "value": i.nid} for i in typy],
# "qualificat": [{"label": i.name, "value": i.nid} for i in qualificat],
# "quoted": [{"label": i.name, "value": i.nid} for i in quoted],
# "financ": [{"label": i.name, "value": i.nid} for i in financ],
# "buildate": [{"label": "1-3年", "value": 1}, {"label": "3-5年", "value": 2},
# {"label": "5-8年", "value": 3}, {"label": "8-10年", "value": 4},
# {"label": "10-15年", "value": 5}, {"label": "15年以上", "value": 6}],
# "capital": [{"label": "100万以内", "value": 1}, {"label": "100万-500万", "value": 2},
# {"label": "500万-1000万", "value": 3}, {"label": "1000万-5000万", "value": 4},
# {"label": "5000万-1亿", "value": 5}, {"label": "1亿以上", "value": 6}]
# }
#
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DBERR, msg="数据库查询错误")
# return jsonify(code=RET.OK, msg="获取成功", options=data)
#
#
# # 通过like查询
# def find_up(name_query, relation, area):
# if relation == "中游行业":
# relation_c = "下位产品"
# else:
# relation_c = relation
#
# sql = "match (n) -[r:`{}`]->(m) WHERE n.name='{}' return n.name,r.type,m.name".format(relation_c, name_query)
# res = graph.run(sql).data()
# # cnums = Enterprise.query.filter_by(stream="{}".format(relation[:2]), c_type=inid).count()
#
# data = {"clickable": False,
# "node": "{}".format(relation[:2]),
# "level": 1,
# "subNodeList": [],
# # "count": cnums
# }
# past = list()
# for it in res:
# productName = it["m.name"]
# if productName in past:
# continue
# past.append(productName)
# if area[0]:
# enterprise = Enterprise.query.filter_by(province=area[0])
# if area[1]:
# enterprise = enterprise.filter_by(city=area[1])
# if area[2]:
# enterprise = enterprise.filter_by(district=area[2])
# enterprise = enterprise.filter(Enterprise.product_all.like("%{}%".format(productName)))
# else:
# enterprise = Enterprise.query.filter(Enterprise.product_all.like("%{}%".format(productName)))
#
# erjicount = enterprise.count()
# node = {"clickable": True,
# "node": "{}".format(productName),
# "level": 2,
# "count": erjicount,
# "subNodeList": []
# }
# sql_02 = "match (n) -[r]->(m) WHERE n.name='{}' return n.name,r.type,m.name".format(productName)
# result = graph.run(sql_02).data()
#
# for item in result:
# productName = item["m.name"]
#
# if area[0]:
# enterprise = Enterprise.query.filter_by(province=area[0])
# if area[1]:
# enterprise = enterprise.filter_by(city=area[1])
# if area[2]:
# enterprise = enterprise.filter_by(district=area[2])
# enterprise = enterprise.filter(Enterprise.product_all.like("%{}%".format(productName)))
# else:
# enterprise = Enterprise.query.filter(Enterprise.product_all.like("%{}%".format(productName)))
#
# count = enterprise.count()
#
# erjicount += count
# node["subNodeList"].append({"clickable": True,
# "node": "{}".format(productName),
# "level": 3,
# "count": count,
# "subNodeList": []
# })
# node["count"] = erjicount
# data["subNodeList"].append(node)
#
# return data
#
#
# # 创建body
# def create_body(args_query, args_term):
# body = {
# "query": {
# "bool": {
# "must": [{"multi_match": {"query": "{}".format(args_query["query"]), # match_phrase来实现完全匹配查询。
# "type": "phrase",
# "fields": [
# "product"
# ],
# "slop": 0,
# }
# },
# ]
# }
# },
# "from": 0,
# "size": 10,
# "sort": [],
# "aggs": {},
# "_source": ['company_name'],
#
# }
#
# for k, v in args_term.items():
# body["query"]["bool"]["must"].append({"term": {"{}".format(k): "{}".format(v)}})
#
# return body
#
#
# # 通过es全匹配查询
# def find_up_by_es(name_query, relation, area):
# if relation == "中游行业":
# relation_c = "下位产品"
# else:
# relation_c = relation
#
# args_term = dict() # 省市区条件
# if area[0]:
# args_term['province'] = area[0]
# if area[1]:
# args_term['city'] = area[1]
# if area[2]:
# args_term['district'] = area[2]
# url = "http://127.0.0.1:9200/ty_cur/_search"
#
# sql = "match (n) -[r:`{}`]->(m) WHERE n.name='{}' return n.name,r.type,m.name".format(relation_c, name_query)
# res = graph.run(sql).data()
# res = list(set([i["m.name"] for i in list(res)])) # 不重复的一级节点
# data = {"clickable": False,
# "node": "{}".format(relation[:2]),
# "level": 1,
# "subNodeList": [],
# # "count": cnums
# }
#
# for it in res:
# productName = it
#
# # es全匹配查询企业数量
# args_query = dict() # 产品
# args_query["query"] = productName
# body = create_body(args_query, args_term)
# result_es = json.loads(requests.post(url=url, json=body).text)
# erjicount = int(result_es["hits"]["total"])
#
# node = {"clickable": True,
# "node": "{}".format(productName),
# "level": 2,
# "count": erjicount,
# "subNodeList": []
# }
# sql_02 = "match (n) -[r]->(m) WHERE n.name='{}' return n.name,r.type,m.name".format(productName)
# result = graph.run(sql_02).data()
#
# for item in result:
# productName = item["m.name"]
# # es全匹配查询企业数量
# args_query = dict() # 产品
# args_query["query"] = productName
# body = create_body(args_query, args_term)
# result_es = json.loads(requests.post(url=url, json=body).text)
# count = int(result_es["hits"]["total"])
#
# erjicount += count
# node["subNodeList"].append({"clickable": True,
# "node": "{}".format(productName),
# "level": 3,
# "count": count,
# "subNodeList": []
# })
# node["count"] = erjicount
# data["subNodeList"].append(node)
#
# return data
#
#
# # 通过es全匹配查询三级
# def find_thr_by_es(inid, name_query, relation, area):
# if relation == "中游行业":
# relation_c = "下位产品"
# else:
# relation_c = relation
#
# args_term = dict() # 省市区条件
# if area[0]:
# args_term['province'] = area[0]
# if area[1]:
# args_term['city'] = area[1]
# if area[2]:
# args_term['district'] = area[2]
# args_term['c_type'] = inid # 指定二级企业分类
# # url = "http://127.0.0.1:9200/ty_cur/_search"
# # url = "http://127.0.0.1:9200/ty_all_enterprise/_search"
# url = "http://127.0.0.1:9200/ty_enterprise/_search"
#
# sql_01 = "match (n) -[r:`{}`]->(m) WHERE n.name='{}' return n.name,r.type,m.name".format(relation_c, name_query)
# res_zero = graph.run(sql_01).data()
# res_one = list(set([i["m.name"] for i in list(res_zero)])) # 不重复的一级节点
# data = {"clickable": False,
# "node": "{}".format(relation[:2]),
# "level": 1,
# "subNodeList": [],
# # "count": cnums
# }
#
# for it in res_one:
# pname_one = it
#
# # es全匹配查询企业数量
# args_query = dict() # 产品
# args_query["query"] = pname_one
# body = create_body(args_query, args_term)
# result_es = json.loads(requests.post(url=url, json=body).text)
# erjicount = int(result_es["hits"]["total"])
#
# node_one = {"clickable": True,
# "node": "{}".format(pname_one),
# "level": 2,
# "count": erjicount,
# "subNodeList": []
# }
# sql_02 = "match (n) -[r]->(m) WHERE n.name='{}' return n.name,r.type,m.name".format(pname_one)
# result = graph.run(sql_02).data()
# result = list(set([i["m.name"] for i in list(result)])) # 不重复的二级节点
# for item in result:
# pname_two = item
# # es全匹配查询企业数量
# args_query = dict() # 产品
# args_query["query"] = pname_two
# body = create_body(args_query, args_term)
# result_es = json.loads(requests.post(url=url, json=body).text)
# count2 = int(result_es["hits"]["total"])
# # 二级节点
# node_two = {"clickable": True,
# "node": "{}".format(pname_two),
# "level": 3,
# "count": count2,
# "subNodeList": []
# }
# sql_03 = "match (n) -[r]->(m) WHERE n.name='{}' return n.name,r.type,m.name".format(pname_two)
# result3 = graph.run(sql_03).data()
# result3 = list(set([i["m.name"] for i in list(result3)])) # 不重复的三级节点
# for itm in result3:
# pname_thr = itm
# args_query = dict() # 产品
# args_query["query"] = pname_thr
# body = create_body(args_query, args_term)
# result_es = json.loads(requests.post(url=url, json=body).text)
# count3 = int(result_es["hits"]["total"])
# # 三级
# node_thr = {"clickable": True,
# "node": "{}".format(pname_thr),
# "level": 4,
# "count": count3,
# "subNodeList": []
# }
# node_two["subNodeList"].append(node_thr)
# node_one["subNodeList"].append(node_two)
# data["subNodeList"].append(node_one)
#
# return data
#
#
# # 行业产品公司数量(链图)
# @api_map.route('/attract/chain', methods=['POST'])
# # @login_required
# def attract_chain():
# '''行业id->行业链标题-》上中下游-》查询数值'''
# req_dict = request.get_json()
# inid = req_dict.get("inid") # 二级行业id(二级行业显示链图)
# area = req_dict.get("area") # ["","",""] 省市区
#
# # 校验参数完整性
# if not all([inid]):
# return jsonify(code=RET.PARAMERR, msg="参数不完整")
#
# try:
# name_query = "att" + str(inid) + str("".join(area))
# if redis_store.get(name_query) is not None:
# data = json.loads(redis_store.get(name_query))
# return jsonify(code=RET.OK, msg="获取成功", data=data)
#
# # 行业使用名
# industryName = Industry.query.filter_by(nid=inid).first().oname
# ptp = neo4j_dict()
#
# if industryName in ptp:
# industryName = ptp[industryName]
# result = {
# "industryChain": industryName,
# "nodeList": [find_thr_by_es(inid, industryName, "上游行业", area),
# find_thr_by_es(inid, industryName, "中游行业", area),
# find_thr_by_es(inid, industryName, "下游行业", area)]
# }
# # redis缓存
# redis_store.set(name_query, json.dumps(result))
# redis_store.expire(name_query, 30 * 24 * 3600)
# print("redis")
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DBERR, msg="数据异常")
#
# return jsonify(code=RET.OK, msg="获取成功", data=result)
#
#
# # 全国企业信息详情(已经启用,改用360页企业详情)
# @api_map.route('/enterprise/detail', methods=['POST'])
# @login_required
# def enter_detail():
# '''
# 企业信息详情
# :return:
# '''
# # 获取用户id
# token = request.headers["token"]
# user = verify_token(token)
# user_id = user.id # 用户id
#
# req_dict = request.get_json()
# _id = req_dict.get("id") # 企业id
#
# # 校验参数完整性
# if not all([_id]):
# return jsonify(code=RET.PARAMERR, msg="参数不完整")
#
# try:
# company = Enterprise.query.get(_id)
# user = User.query.get(user_id) # 获取关注列表
# if user:
# enters_ids = [coms.id for coms in user.enterprise]
# else:
# enters_ids = []
# if company:
# data = {"id": company.id,
# "company_name": company.company_name,
# "telephone": company.telephone if company.telephone else "-",
# "web_site": company.web_site if company.web_site else "-",
# "email": company.email if company.email else "-",
# "address": company.address if company.address else "-",
# "jwd": {"lng": company.lng if company.lng else "-",
# "lat": company.lat if company.lat else "-"},
# "company_info": company.company_info if company.company_info else "-",
# "high_new": "高新技术企业" if company.high_new else "-",
# "legal": company.legal if company.legal else "-",
# "status": company.status if company.status else "-",
# "build_date": str(company.build_date)[:10] if company.build_date else "-",
# "capital": company.capital if company.capital else "-",
# "social_code": company.social_code if company.social_code else "-",
# "taking": company.takingn if company.takingn else "-",
# "bao": company.bao_num if company.bao_num else "-",
# "entype": company.entype if company.entype else "-",
# "industry": company.company_industry if company.company_industry else "-",
# "scope": company.business_scope if company.business_scope else "-",
# "collect": "1" if company.id in enters_ids else "2", # 关注状态码1关注,2未关注
# "choice": "2" # 1太原企业,2全国企业
# }
# else:
# return jsonify(code=RET.NODATA, msg="查无数据")
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(code=RET.DBERR, msg="数据库查询错误")
# return jsonify(code=RET.OK, msg="获取成功", data=data)
......@@ -544,9 +544,11 @@ class Induzone(db.Model):
# warter_point = db.Column(db.Float, doc='水费的评分', comment='水费的评分') # 水费的评分
# electricity_point = db.Column(db.Float, doc='电费的评分', comment='电费的评分') # 电费的评分()
school_point = db.Column(db.Float, doc='高校院所的评分', comment='高校院所的评分') # 高校院所的评分
policy_point = db.Column(db.Float, doc='政策数的评分', comment='政策数的评分') # 政策数的评分
live_point = db.Column(db.Float, doc='生活配套的评分', comment='生活配套的评分') # 高校院所的评分
traffic_point = db.Column(db.Float, doc='交通的评分', comment='交通的评分') # 高校院所的评分
mall_point = db.Column(db.Float, doc='购物中心的评分', comment='购物中心的评分') # 购物中心的评分
hotel_point = db.Column(db.Float, doc='酒店餐饮的评分', comment='酒店餐饮的评分') # 酒店餐饮的评分
policy_point = db.Column(db.Float, doc='政策数的评分', comment='政策数的评分') # 政策数的评分
development_zone = db.Column(db.String(255), doc='所在开发区', comment='所在开发区') # 所在开发区
# 项目列表
......@@ -942,7 +944,15 @@ class EvaluationNodeData(db.Model):
score = db.Column(db.Integer, doc='综合分', comment='综合分') # 综合分
# 选址评分部分--企业聚合度
class CompanyIndustryPoint(db.Model):
__tablename_ = "company_industry_point"
__table_args__ = ({'comment': '选址评分部分--企业聚合度数据表'}) # 添加表注释
id = db.Column(db.Integer, primary_key=True, autoincrement=True, doc='主键id', comment='主键id')
district = db.Column(db.String(32), doc='区县园区名', comment='区县园区名') # 区县园区名
point = db.Column(db.Float, doc='分数', comment='分数') # 分数
f_type = db.Column(db.Integer, doc='类型,对应产业导航nid', comment='类型,对应产业导航nid') # 类型,对应产业导航nid
......@@ -1000,14 +1010,7 @@ class EvaluationNodeData(db.Model):
# # 选址评分部分--企业聚合度
# class CompanyIndustryPoint(db.Model):
# __tablename_ = "company_industry_point"
#
# id = db.Column(db.Integer, primary_key=True, autoincrement=True)
# district = db.Column(db.String(32)) # 区县园区名
# point = db.Column(db.Float) # 分数
# f_type = db.Column(db.Integer) # 类型,对应产业导航nid
#
#
# # # 园区政策
......@@ -1055,7 +1058,7 @@ class EvaluationNodeData(db.Model):
#
# # 招商资源管理字典(行业选择,项目阶段)
# class Attract(db.Model):
# __tablename_ = "attract"
# __tablename_ = "attract_map"
#
# id = db.Column(db.Integer, primary_key=True, autoincrement=True)
# name = db.Column(db.String(32)) # 字段名
......
......@@ -686,7 +686,7 @@ def newList():
#
#
# # 行业产品公司数量(链图)
# @api_radar.route('/attract/chain', methods=['POST'])
# @api_radar.route('/attract_map/chain', methods=['POST'])
# # @login_required
# def attract_chain():
# '''行业id->行业链标题-》上中下游-》查询数值'''
......
......@@ -2,8 +2,8 @@ from py2neo import Graph
def conn_neo4j():
# graph = Graph("http://localhost:7474", username="neo4j", password="123456") # 本地neo4j
graph = Graph("http://localhost:7476", username="neo4j", password="123456") # 上传到50服务器前需更改
graph = Graph("http://localhost:7474", username="neo4j", password="123456") # 本地neo4j
# graph = Graph("http://localhost:7476", username="neo4j", password="123456") # 上传到50服务器前需更改
# graph = Graph("http://39.100.39.50:7476/", username="neo4j", password="123456") # 测试50服务器上的neo4j时使用
return graph
......
from flask import Blueprint
# 招商驾驶舱
api_attract = Blueprint("api_attract", __name__)
from . import view # 招商驾驶舱数据
from . import view_changedata # 修改招商驾驶舱数据(区域宏观经济、作战图、项目产业分布图)
import json
import os
import sys
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkvod.request.v20170321.GetPlayInfoRequest import GetPlayInfoRequest
from flask import request, jsonify, session, current_app
from sqlalchemy import func, desc, or_
from apps.models import *
from apps.view_attract import api_attract
from apps.utils.response_code import RET
from apps import db, constants, redis_store
# 获取左上角经济指标数据
def get_jjzb(district):
'''经济指标数据'''
# years = [2021] # 指定数据的年份,与数据库中数据对齐
try:
if not district or district == '晋城市':
datas = City.query.filter_by(area='晋城市').first()
else:
datas = City.query.filter_by(area=district).first()
df_dic = {"GDP": '%.2f亿元' % (datas.GDP / 10000) if datas.GDP else "-亿元", # 地区生产总值
"addscale": '%.2f' % datas.addscale + "%" if datas.addscale else "-%", # 规上工业增加值增速
"investment": '%.2f亿元' % (datas.investment / 10000) if datas.investment else "-亿元", # 固定资产投资
"retail": '%.2f亿元' % (datas.retail / 10000) if datas.retail else "-亿元", # 社会消费品零售额
"in_out": '%.2f亿元' % (datas.in_out / 10000) if datas.in_out else "-亿元", # 进出口总额
"public": '%.2f亿元' % (datas.public / 10000) if datas.public else "-亿元", # 一般公共预算支出
"people_out": '%.2f元' % datas.people_out if datas.people_out else "-元", # 居民人均可支配收入
"people_per": '%.2f' % datas.people_per if datas.people_per else "-"} # 居民消费价格指数
# print(df_dic)
# return jsonify(code=RET.OK, msg="查找成功", data=df)
return df_dic
# return df
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
@api_attract.route("/index", methods=["GET"])
def index():
return '德旭,你好!'
# 左上角企业数量各资质统计、左上角获取经济指标数据、产业机构分布饼状图数据统计
@api_attract.route("/menu", methods=["POST"])
def menu():
'''左上角企业数量各资质统计、左上角获取经济指标数据、产业机构分布饼状图数据统计'''
req_dict = request.get_json()
district = req_dict.get("district") # 区县或者开发区名称
# 区县名称转换字典
district_dict = {
'沁水县': '沁水县',
'高平市': '高平市',
'陵川县': '陵川县',
'阳城县': '阳城县',
'泽州县': '泽州县',
'城区': '城区',
'晋城经济技术开发区': '晋城经济技术开发区'
}
if not district or district == '晋城市':
try:
company = Company.query.filter_by(city="晋城市")
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
else:
try:
# company = Company.query.filter(Company.induzone == district_dict[district], Company.city == "晋城市")
company = Company.query.filter(Company.district == district_dict[district], Company.city == "晋城市")
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
# 1. 左上角企业数量各资质统计
try:
# 晋城市
t_c5 = company.filter_by(isfive="1").count() # 500强
ssqy = company.filter_by(quoted_company="1").count() # 上市
if district != "晋城市":
gmys = Company.query.filter(Company.induzone == district_dict[district]).filter_by(
scale="1").count() # 规模(2-5) 622
else:
gmys = Company.query.filter_by(scale="1").count()
zjtx = company.filter_by(zjtg="1").count() # 专精特新
gxjs = company.filter_by(high_new="1").count() # 高新
kjzx = company.filter_by(tbe="1").count() # 科技型中小企业
dengl = company.filter_by(dengl="1").count() # 瞪羚
dujs = company.filter_by(unicorn="1").count() # 独角兽
table_dic = {"t_c5": t_c5, # 500强企业
"ssqy": ssqy, # 上市企业
"gmys": gmys, # 规模以上企业
"zjtx": zjtx, # 专精特新企业
"gxjs": gxjs, # 高新技术企业
"kjzx": kjzx, # 科技型中小企业
"dengl": dengl, # 瞪羚企业
"dujs": dujs} # 独角兽企业
# 2. 左上角获取经济指标数据
jjzb_data = get_jjzb(district)
# 3. 产业结构分布饼状图数据统计
count_all = company.count()
if count_all == 0:
count_all = 1
count_mcq = company.filter_by(f_type=1).count() # 煤层气
count_gjd = company.filter_by(f_type=3).count() # 光机电
count_mtmhg = company.filter_by(f_type=4).count() # 煤炭煤化工
count_gtzz = company.filter_by(f_type=2).count() # 钢铁铸造
count_qyly = company.filter_by(f_type=5).count() # 全域旅游和康养
# count_xdfu = company.filter_by(f_type=6).count() # 现代服务业
# count_qt = count_all - count_mcq - count_gjd - count_mtmhg - count_gtzz - count_qyly - count_xdfu
count_qt = count_all - count_mcq - count_gjd - count_mtmhg - count_gtzz - count_qyly
mcq = int(count_mcq / count_all * 100)
gjd = int(count_gjd / count_all * 100)
mtmhg = int(count_mtmhg / count_all * 100)
gtzz = int(count_gtzz / count_all * 100)
qyly = int(count_qyly / count_all * 100)
# xdfu = int(count_xdfu / count_all * 100)
# qt = 100 - mcq - gjd - mtmhg - gtzz - qyly - xdfu
qt = 100 - mcq - gjd - mtmhg - gtzz - qyly
# 产业结构分布
industry = [
{"per": mtmhg, "name": "煤炭煤化工", "count": count_mtmhg},
{"per": mcq, "name": "煤层气", "count": count_mcq}, # {百分比,value}
{"per": gjd, "name": "光机电", "count": count_gjd},
{"per": gtzz, "name": "钢铁铸造", "count": count_gtzz},
{"per": qyly, "name": "全域旅游和康养", "count": count_qyly},
{"per": qt, "name": "其他", "count": count_qt},
]
# TODO 4.五大千亿级产业集群
data = {
"jjzb_dic": jjzb_data, # 左上角经济指标数据
"table_dic": table_dic, # 左上角企业数据统计
"industry_dic": industry # 产业结构分布饼状图数据
}
return jsonify(code=RET.OK, msg="查找成功", data=data)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
# 招商引资作战图、项目数量/金额分布图
@api_attract.route("/project", methods=["POST"])
def project():
req_dict = request.get_json()
district = req_dict.get("district") # 区县或者开发区名称
try:
project_map = []
industry_money = []
industry_nums = []
list1 = ["晋城市", "沁水县", "高平市", "陵川县", "阳城县", "泽州县", "城区", "晋城经济技术开发区"]
# 晋城市,点击区县之前默认数据
if not district or district == '晋城市':
for i in list1:
# 1.招商引资作战图数据
ss = Examine.query.filter_by(district=i).first()
project_map.append({"name": i,
"nums1": "{}亿元".format(ss.sign_finnish),
"add1": ss.sign_grade,
"nums2": "{}亿元".format(ss.start_finish),
"add2": ss.start_grade,
"nums3": "{}亿元".format(ss.invest_finish),
"add3": ss.invest_grade
})
# 产业数量/金额分布图数据
# types_list = []
# industry_dic = {}
project_list = NewProject.query.filter_by(district="晋城市").all()
i = 0
for project in project_list:
i += 1
if i > 6:
pass
else:
industry_money.append({"name": project.type,
"value": project.money})
industry_nums.append({"name": project.type,
"value": project.number})
# 点击区县后的联动数据
else:
# 1.招商引资作战图数据
ss = Examine.query.filter_by(district=district).first()
project_map.append({"name": district,
"nums1": "{}亿元".format(ss.sign_finnish),
"add1": ss.sign_grade,
"nums2": "{}亿元".format(ss.start_finish),
"add2": ss.start_grade,
"nums3": "{}亿元".format(ss.invest_finish),
"add3": ss.invest_grade
})
# 产业数量/金额分布图数据
i = 0
project_list = NewProject.query.filter_by(district=district).all()
for project in project_list:
i += 1
if i > 6:
pass
else:
industry_money.append({"name": project.type,
"value": project.money})
industry_nums.append({"name": project.type,
"value": project.number})
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
data = {
"project_map": project_map, # 招商引资作战图
"industry_nums": industry_nums, # 已签约项目数量产业分布图
"industry_money": industry_money, # 已签约项目投资金额产业分布图
}
return jsonify(code=RET.OK, msg="获取成功", data=data)
# 政策和重点项目
@api_attract.route("/propol", methods=["POST"])
def propol():
req_dict = request.get_json()
district = req_dict.get("district") # 县区
try:
if not district or district == "晋城市":
# name_query = "project-propol"
# if redis_store.get(name_query) is not None:
# data = json.loads(redis_store.get(name_query))
# return jsonify(code=RET.OK, msg="获取成功", data=data)
project = Project.query.all()
policy = InduPolicy.query.filter_by(district="晋城市").order_by(InduPolicy.pubdate.desc())
data_policy = [{"name": i.name, "id": i.id, "distict": "太原市"} for i in policy.all()]
data_project = [{"name": i.name, "id": i.id} for i in project]
data = {
"project": data_project,
"policy": data_policy,
}
# redis缓存
# redis_store.set(name_query, json.dumps(data))
# redis_store.expire(name_query, 1 * 24 * 3600)
else: # 区县、开发区
project = Project.query.filter_by(district=district)
policy = InduPolicy.query.filter_by(district=district).order_by(InduPolicy.pubdate.desc())
data_policy = [{"name": i.name, "id": i.id, "distict": district} for i in policy.all()]
data_project = [{"name": i.name, "id": i.id} for i in project.all()]
data = {
"project": data_project, # 重点项目
"policy": data_policy, # 政策
}
return jsonify(code=RET.OK, msg="查询成功", data=data)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DATAERR, msg="数据库错误")
# 获取区县的详情
@api_attract.route("/getInfo", methods=["POST"])
def get_info():
req_dic = request.get_json()
district = req_dic.get("district") # 地区
if not district:
return jsonify(code=RET.PARAMERR, msg="参数不完整")
try:
city = City.query.filter_by(area=district).first()
info = city.info
detail_dic = {
"detail_data": info
}
return jsonify(code=RET.OK, msg="查询成功", data=detail_dic)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
# 获取区县视频url
@api_attract.route("/video", methods=["POST"])
def attract_video():
req_dic = request.get_json()
district = req_dic.get("district")
if not district:
return jsonify(code=RET.PARAMERR, msg="参数不全")
# district_dict = {'晋城市': '晋城市',
# '沁水市': '沁水市',
# '高平市': '高平市',
# '陵川市': '陵川市',
# '阳城市': '阳城市',
# '泽州市': '泽州市',
# '城区': '城区'
# }
try:
video = Video.query.filter_by(district=district).first()
except Exception as e:
current_app.logger.error(e)
if video:
url = video.video_id1
if url:
return jsonify(code=RET.OK, msg="查询成功", data={"url": url})
else:
return jsonify(code=RET.DATAERR, msg="区县名称有误,没有相关视频")
return jsonify(code=RET.NODATA, msg="暂无视频", data={"url": ""})
# 获取重点项目的详情,详情页
@api_attract.route("/keyProject", methods=["POST"])
def keyproject():
req_dic = request.get_json()
id = req_dic.get("id")
if not id:
return jsonify(code=RET.PARAMERR, msg="参数不完整")
try:
project = Project.query.get(id)
data = {
"name": project.name, # 工程名
"district": project.district, # 区县名称
"type": project.type, # 工程类型
"money": project.money, # 项目投资金额
"background": project.background, # 项目背景
"content": project.content, # 项目的具体内容
"way": project.way, # 拟引资方式及内容
"company": project.company, # 招商单位
"contact": project.contact, # 联系方式
"email": project.email # 电子邮箱
}
return jsonify(code=RET.OK, msg="查找成功", data=data)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
# 政策详情
@api_attract.route("/policyDetails", methods=["POST"])
def policy_details():
req_dic = request.get_json()
_id = req_dic.get("id")
if not _id:
return jsonify(code=RET.PARAMERR, msg="参数不全")
try:
_id1 = int(_id) + 1
_id2 = int(_id) - 1
if _id2 < 1:
_id2 = ''
policy_len = InduPolicy.query.count()
if _id1 > policy_len:
_id1 = ''
policy = InduPolicy.query.get(_id)
policy1 = InduPolicy.query.get(str(_id1))
policy2 = InduPolicy.query.get(str(_id2))
if policy:
data = {"name": policy.name, # 政策名
"file": policy.file if policy.file else "-", # 本地文件位置
"category": policy.category if policy.category else "-", # 政策类型
"org": policy.org if policy.org else "-", # 政策发布机构
"industry": policy.industry if policy.industry else "-", # 行业名称
"district": policy.district if policy.district else "-", # 政策发布地区
"pubdate": str(policy.pubdate)[0:10] if policy.pubdate else "-", # 发布时间
"url": policy.url if policy.pubdate else "-", # 外链接
"post_num": policy.post_num if policy.post_num else "", # 发文字号
"last": [policy2.name, _id1] if policy2 else "",
"next": [policy1.name, _id2] if policy1 else ""}
return jsonify(code=RET.OK, msg="查找成功", data=data)
else:
return jsonify(code=RET.OK, msg="查找成功,无数据", data='')
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
# 列表展示左上角企业
@api_attract.route("/showListb", methods=["POST"])
def showListb():
req_dic = request.get_json()
type = req_dic.get("type") # 12345678 (500强-上市-规模-专精特新-高新-科技中小-瞪羚-独角兽)
district = req_dic.get("district")
page = req_dic.get("page")
per_page = req_dic.get("per_page")
if not all([type, district]):
return jsonify(code=RET.PARAMERR, msg="参数错误")
if not page:
page = 1
try:
# 企业
if district == "晋城市":
company = Company.query.filter_by(city="晋城市")
else:
company = Company.query.filter_by(city="晋城市", district=district)
size = company.count()
if type == 1:
company = company.filter_by(isfive=1)
size = company.count()
if type == 2:
company = company.filter_by(quoted_company=1)
size = company.count()
if type == 3:
if district == "晋城市":
company = Company.query.filter_by(scale="1")
else:
company = Company.query.filter_by(district=district, scale="1")
size = company.count()
if type == 4:
company = company.filter_by(zjtg=1)
size = company.count()
if type == 5:
company = company.filter_by(high_new=1)
size = company.count()
if type == 6:
company = company.filter_by(tbe=1)
size = company.count()
if type == 7:
company = company.filter_by(dengl=1)
size = company.count()
if type == 8:
company = company.filter_by(unicorn=1)
size = company.count()
company = company.paginate(page, per_page=int(per_page)).items
data = [{
"id": i.id,
"name": i.company_name,
"industry": i.company_industry if i.company_industry else "-",
"product": i.product if i.product else "-",
"build_date": "-",
"capital": i.capital if i.capital else "-",
"isfive": "500强企业" if i.isfive == "1" else "",
"quoted_company": i.public_sector if i.public_sector != "空" else "",
"scale": "规模以上企业" if i.scale == "1" else "",
"zjtg": "专精特新企业" if i.zjtg == "1" else "",
"high_new": "高新技术企业" if i.high_new == "1" else "",
"tbe": "科技型中小企业" if i.tbe == "1" else "",
"dengl": "瞪羚企业" if i.dengl == "1" else "",
"unicorn": "独角兽企业" if i.unicorn == "1" else "",
} for i in company]
data = {"data_list": data, "size": size}
return jsonify(code=RET.OK, msg="查找成功", data=data)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
# 企业信息详情(招商驾驶舱左上角各类企业详情)
@api_attract.route('/companyDetail', methods=['POST'])
def enterprise_detail():
'''
企业信息详情
:return:
'''
req_dict = request.get_json()
id = req_dict.get("id") # 企业id
# 校验参数完整性
if not all([id]):
return jsonify(code=RET.PARAMERR, msg="参数不完整")
try:
company = Company.query.get(id)
# 工商状况-查询行政许可数据
data_info1 = CompanyAdminPermission.query.filter_by(company_id=id).all()
# 工商状况-查询税务信用数据
data_info2 = CompanyTaxCredit.query.filter_by(company_id=id).all()
# 工商状况-查询进出口信用数据
data_info3 = CompanyImportExport.query.filter_by(company_id=id).all()
# 工商状况-查询供应商数据信息
data_info4 = CompanySupplier.query.filter_by(company_id=id).all()
# 工商状况-查询客户数据信息
data_info5 = CompanyCustomer.query.filter_by(company_id=id).all()
# 企业风险-查询股权出质数据信息
data_info6 = CompanyStock.query.filter_by(company_id=id).all()
# 企业风险-查询股权质押数据信息
data_info7 = CompanyPledge.query.filter_by(company_id=id).all()
# 企业风险-查询担保信息数据信息
data_info8 = CompanyDanbao.query.filter_by(company_id=id).all()
# 知识产权-查询专利信息数据信息
data_info9 = CompanyPatent.query.filter_by(company_id=id).all()
# 供应链图谱数据
# 供应链地图
supplier = CompanySupplier.query.filter_by(company_id=id).all()
if company:
data = {"select1_info": {"id": company.id,
"company_name": company.company_name, # 企业名
"telephone": company.telephone if company.telephone else "-", # 电话
"web_site": company.web_site if company.web_site else "-", # 网址
"email": company.email if company.email else "-", # 邮箱
"address": company.address if company.address else "-", # 地址
"jwd": {"lng": company.lng if company.lng else "-", # 经度
"lat": company.lat if company.lat else "-"}, # 维度
"company_info": company.company_info if company.company_info else "-", # 企业信息
"business_scope": company.business_scope if company.business_scope else "-",
# 经营范围
"high_new": "高新技术企业" if company.high_new else "-", # 高新技术企业
"legal": company.legal if company.legal else "-", # 法定代表人
"status": company.status if company.status else "-", # 状态
"build_date": str(company.build_date)[:10] if company.build_date else "-", # 创建时间
"capital": company.capital if company.capital else "-", # 注册资本
"social_code": company.social_code if company.social_code else "-", # 统一社会信用代码
# "taking": company.takingn if company.takingn else "-", # 营收 (万元)
"bao": company.bao_num if company.bao_num else "-", # 参保人数
"entype": company.entype if company.entype else "-", # 企业类型
"industry": company.company_industry if company.company_industry else "-", # 所属行业
"scope": company.business_scope if company.business_scope else "-", # 企业经营范围
# "collect": "1",
# "choice": "3"
"tax_code": company.tax_code if company.tax_code else "-",
"register_code": company.register_code if company.register_code else "-",
},
# 经营状况数据封装
"select2_info": {
"select2_info_name": '经营状况数据',
"label1": [{
"label1_name": '行政许可',
"number": data.number,
"name": data.name,
"time": (data.time).strftime("%Y-%m-%d %H:%M:%S"),
"effective_data": (data.effective_data).strftime("%Y-%m-%d %H:%M:%S"),
"Licensing_authority": data.Licensing_authority,
"content": data.content,
"source": data.source} for data in data_info1 if data_info1],
"label2": [{
"label2_name": '税务信用',
"evaluation_annual": data.evaluation_annual,
"identify_number": data.identify_number,
"level": data.level,
"evaluate": data.evaluate} for data in data_info2 if data_info2],
"label3": [{
"label3_name": '进出口信用',
"register_customs": data.register_customs,
"business_category": data.business_category,
"register_date": (data.register_date).strftime("%Y-%m-%d %H:%M:%S")} for data in data_info3 if data_info3],
"label4": [{
"label4_name": '供应商',
"supplier_name": data.supplier_name,
"buy_rate": data.buy_rate,
"buy_money": data.buy_money,
"open_time": (data.open_time).strftime("%Y-%m-%d %H:%M:%S"),
"data_source": data.data_source,
"relation": data.relation} for data in data_info4 if data_info4],
"label5": [{
"label5_name": '客户',
"customer_name": data.customer_name,
"sales_rate": data.sales_rate,
"sales_money": data.sales_money,
"open_time": (data.open_time).strftime("%Y-%m-%d %H:%M:%S"),
"data_source": data.data_source,
"relation": data.relation} for data in data_info5 if data_info5]
},
# 企业风险数据封装
"select3_info": {
"select3_info_name":'企业风险数据',
"label1": [{
"label1_name": '股权出质',
"num": data.num,
"person": data.person,
"from_company": data.from_company,
"pledgee": data.pledgee,
"amount": data.amount,
"datatime": (data.datatime).strftime("%Y-%m-%d %H:%M:%S"),
"status": data.status
} for data in data_info6 if data_info6],
"label2": [{
"label2_name": '股权质押',
"person1": data.person1,
"jion_company": data.jion_company,
"person2": data.person2,
"number": data.number,
"amount": data.amount,
"status": data.status,
"datatime": (data.datatime).strftime("%Y-%m-%d %H:%M:%S")
} for data in data_info7 if data_info7],
"label3": [{
"label3_name": '担保信息',
"person1": data.person1,
"person2": data.person2,
"method": data.method,
"amount": data.amount,
"datatime": (data.datatime).strftime("%Y-%m-%d %H:%M:%S")
} for data in data_info8 if data_info8]
},
# 知识产权数据封装
"select4_info": {
"select4_info_name":'专利信息',
"label": [{
"label_name": '专利信息',
"name": data.name,
"type": data.type,
"status": data.status,
"num": data.num,
"day": (data.day).strftime("%Y-%m-%d %H:%M:%S"),
"open_num": data.open_num,
"datatime": (data.datatime).strftime("%Y-%m-%d %H:%M:%S"),
"person": data.person
} for data in data_info9 if data_info9]
},
# 供应链图谱数据封装
"select5_info": {
},
# 供应链地图封装
"select6_info": {
"company_data": {"company_name": company.company_name,
"company_lat": company.lat,
"company_lng": company.lng,
"supplier": [{"supplier_name": i.supplier_name, 'lat': i.lat, 'lng': i.lng}
for i in supplier]}
}
}
else:
return jsonify(code=RET.NODATA, msg="查无数据")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库查询错误")
return jsonify(code=RET.OK, msg="获取成功", data=data)
# # 删除缓存
# @api_attract.route("/deleteX", methods=["GET"])
# def deleteX():
# redis_store.delete("project-propol")
# return jsonify(code=RET.OK, msg="删除成功")
#
#
# # 删除缓存
# @api_attract.route("/vis", methods=["GET"])
# def vis():
# redis_store.delete("project-propol")
# return jsonify(code=RET.OK, msg={"remote_addr": request.remote_addr,
# "X-Real-Ip": request.headers.get("X-Real-Ip"),
# "X-Forwarded-For": request.headers.get("X-Forwarded-For"),
# "HOST": request.headers.get("Host"),
# "X-Forwarded-Proto": request.headers.get("X-Forwarded-Proto"),
# })
import json
from flask import request, jsonify, session, current_app
from sqlalchemy import func, desc, or_
from apps.models import *
from apps.view_attract import api_attract
from apps.utils.response_code import RET
from apps import db, constants, redis_store
# 改变城市数据
@api_attract.route("/changeCityData", methods=["POST"])
def changeCityData():
req_dic = request.get_json()
year = req_dic.get("年份")
district = req_dic.get("区县名称")
GDP = req_dic.get("地区生产总值")
size = req_dic.get("面积")
people = req_dic.get("人口")
investment = req_dic.get("固定资产投资")
retail = req_dic.get("社会消费品零售额")
public = req_dic.get("一般公共预算支出")
addscale = req_dic.get("规上工业增加值增速")
in_out = req_dic.get("进出口总额")
people_out = req_dic.get("居民人均可支配收入")
people_per = req_dic.get("居民消费价格指数")
info = req_dic.get("区县介绍")
if not all([year, district]):
return jsonify(code=RET.PARAMERR, msg="省份和年份是必填参数")
try:
city = City.query.filter_by(area=district, year=2020).first()
if GDP:
city.GDP = GDP
if size:
city.GDP = size
if people:
city.people = people
if investment:
city.investment = investment
if retail:
city.retail = retail
if public:
city.public = public
if addscale:
city.addscale = addscale
if in_out:
city.in_out = in_out
if people_out:
city.people_out = people_out
if people_per:
city.people_per = people_per
if info:
city.info = info
db.session.commit()
return jsonify(code=RET.OK, msg="修改成功")
except Exception as e:
db.session.rollback()
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
@api_attract.route("/addCityData", methods=["POST"])
def addCityData():
req_dic = request.get_json()
year = req_dic.get("年份")
district = req_dic.get("区县名称")
GDP = req_dic.get("地区生产总值")
size = req_dic.get("面积")
people = req_dic.get("人口")
investment = req_dic.get("固定资产投资")
retail = req_dic.get("社会消费品零售额")
public = req_dic.get("一般公共预算支出")
addscale = req_dic.get("规上工业增加值增速")
in_out = req_dic.get("进出口总额")
people_out = req_dic.get("居民人均可支配收入")
people_per = req_dic.get("居民消费价格指数")
info = req_dic.get("区县介绍")
if not all([year, district]):
return jsonify(code=RET.PARAMERR, msg="省份和年份是必填参数")
try:
city = City(area=district, year=year)
if GDP:
city.GDP = GDP
if size:
city.GDP = size
if people:
city.people = people
if investment:
city.investment = investment
if retail:
city.retail = retail
if public:
city.public = public
if addscale:
city.addscale = addscale
if in_out:
city.in_out = in_out
if people_out:
city.people_out = people_out
if people_per:
city.people_per = people_per
if info:
city.info = info
db.session.add(city)
db.session.commit()
return jsonify(code=RET.OK, msg="添加成功")
except Exception as e:
db.session.rollback()
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
@api_attract.route("/updateExamdata", methods=["POST"])
def updateExamdata():
req_dic = request.get_json()
year = req_dic.get("年份")
district = req_dic.get("区县名称")
month = req_dic.get("月份")
sign_finnish = req_dic.get("签约项目投资额完成额")
sign_grade = req_dic.get("签约项目投资额完成率")
start_finish = req_dic.get("开工项目计划投资额完成额")
start_grade = req_dic.get("开工项目计划投资额完成率")
invest_finish = req_dic.get("开工项目到位金额完成额")
invest_grade = req_dic.get("开工项目到位金额完成率")
if not all([district]):
return jsonify(code=RET.PARAMERR, msg="缺少必要参数")
try:
examine = Examine.query.filter_by(district=district)
if sign_finnish:
examine.sign_finnish = sign_finnish * 100
if sign_grade:
examine.sign_grade = sign_grade
if start_finish:
examine.start_finish = start_finish
if start_grade:
examine.start_grade = start_grade
if invest_finish:
examine.invest_finish = invest_finish * 10
if invest_grade:
examine.invest_grade = invest_grade
db.session.commit()
return jsonify(code=RET.OK, msg="修改成功")
except Examine as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg='数据库错误')
# 更新饼图数据
@api_attract.route("/updateNewProject", methods=["POST"])
def updateNewProject():
req_dic = request.get_json()
district = req_dic.get("区县")
type = req_dic.get("行业")
number = req_dic.get("项目个数")
money = req_dic.get("金额")
if not all([district, type]):
return jsonify(code=RET.PARAMERR, msg="缺少必要参数")
try:
newproject = NewProject.query.filter_by(district=district, type=type).first()
if number:
newproject.number = number
if money:
newproject.money = money
db.session.commit()
except Exception as e:
db.session.rollbakck()
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
# 添加饼图数据
@api_attract.route("/addNewProject", methods=["POST"])
def addNewProject():
req_dic = request.get_json()
district = req_dic.get("区县")
type = req_dic.get("行业")
number = req_dic.get("项目个数")
money = req_dic.get("金额")
if not all([district, type, number, money]):
return jsonify(code=RET.PARAMERR, msg="缺少必要参数")
try:
newproject = NewProject.query.filter_by(district=district, type=type).first()
if newproject:
return jsonify(code=RET.DATAEXIST, msg="数据已存在")
newproject = NewProject(district=district, type=type, number=number, money=money)
db.session.add(newproject)
db.session.commit()
except Exception as e:
db.session.rollbakck()
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
from flask import Blueprint
api_address = Blueprint("api_address",__name__)
# from . import view # 旧版
from . import view_choose_address # 新改
from flask import current_app, request, jsonify
from apps.models import *
from apps.utils.response_code import RET
from apps.view_choose_address import api_address
import copy
import pymysql
# 选址评估,选择建议
@api_address.route("/advice", methods=["POST"])
def advice():
req_dict = request.get_json()
company = req_dict.get("company") # 企业名称(无作用)
industry = req_dict.get("industry") # 行业选择 nid
revenue = req_dict.get("revenue") # 营收 "2"
tax = req_dict.get("tax") # 税收 "1"
product = req_dict.get("product") # 主营产品 "药"
budget = req_dict.get('budget') # 预算 "22" # 大于
address = req_dict.get("address") # 地址 "小店区"
preference = req_dict.get("preference") # 选址偏好 [f,f,t,f,f,f]
if not all([company, industry, revenue, tax, product, budget, preference]):
return jsonify(code=RET.DATAERR, msg="数据不全")
list_zone = [] # 拼接sql的列表
if address:
list_zone.append("(region='{}'or development_zone = '{}')".format(address, address)) # 太原园区的字段 Induzone
list_zone.append(" (f_type is Null or f_type = {}) ".format(industry)) # 企业聚合度 CompanyIndustryPoint
list_zone.append("IFNULL(induzone.tax,0)<={}".format(tax)) # 园区税收要求 Induzone
list_zone.append("IFNULL(induzone.invest_power,0)<={}".format(budget)) # 投资强度 Induzone
list_zone = " and ".join(list_zone) # 拼接
sum_list = []
if preference[5] != "false": # 地区经济发展 ---GDP的打分
sum_list.append("IFNULL(induzone.gdp_point,0)")
if preference[1] != "false": # 产业聚集度 --- 产业的打分
# sum_list.append("IFNULL(company_industry_point,0)")
sum_list.append("IFNULL(company_industry_point.point,0)")
if preference[0] != "false": # 征服扶持力度 --- 政策数的打分
sum_list.append("IFNULL(induzone.policy_point,0)")
if preference[3] != "false": # 生活配套 -------水电打分
sum_list.append("IFNULL(induzone.warter_point,0)")
if preference[2] != "false": # 交通 -----交通打分
sum_list.append("IFNULL(induzone.electricity_point,0)")
if preference[4] != "false": # 园区配套服务 ----园区的学校,商业街,宾馆打分
sum_list.append("IFNULL(induzone.mall_point,0)")
sum_list.append("IFNULL(induzone.hotel_point,0)")
sum_list.append("IFNULL(induzone.school_point,0)")
# 拼接where请求
if list_zone:
list_zone = "where " + list_zone
# 拼接排序请求
sum_list = " + ".join(sum_list)
# print(sum_list, "-" * 10)
if sum_list:
sum_list = " order by " + sum_list + " desc"
# sql语句
sql = "select * from induzone " \
"LEFT OUTER JOIN company_industry_point on induzone.name = company_industry_point.district " \
+ list_zone + sum_list
print(sql)
try:
conn = pymysql.connect(host='39.100.39.50',
user='root',
password='Root@2020',
db='indutyty',
charset='utf8mb4')
cursor = conn.cursor()
data_num = cursor.execute(sql)
data_list = cursor.fetchall()
# print(sql)
if data_num > 3:
data_list = data_list[0:3]
data = [{"id": i[0],
"name": i[1],
"charge": i[9] if i[9] else "-",
"phone": i[10] if i[10] else "-",
"jwd": {"lng": i[13], "lat": i[14]}} for i in data_list]
# 没有查询结果的查找
if not data_list:
# 在第一条建议显示
data = [{"name": "对不起,没有找到合适的园区!"}]
cursor.close()
conn.close()
new_preference = copy.deepcopy(preference)
# del new_preference[2]
for i in range(0, len(data)):
if "true" in new_preference:
grade = 0
list_info = []
info = "根据{}算出结果,得分为{}"
s1 = Induzone.query.get(data[i]["id"])
if preference[5] != "false": # 地区经济发展 ---GDP的打分
grade += s1.gdp_point if s1.gdp_point else 0
list_info.append("地区经济发展")
if preference[1] != "false": # 产业聚集度 --- 产业的打分
# sum_list.append("IFNULL(company_industry_point,0)")
ss = CompanyIndustryPoint.query.filter_by(district=data[i]["name"], f_type=industry).first()
grade += ss.point if ss else 0
list_info.append("产业聚集度")
if preference[0] != "false": # 征服扶持力度 --- 政策数的打分
grade += s1.policy_point if s1.policy_point else 0
list_info.append("政府扶持力度")
if preference[3] != "false": # 生活配套 -------水电打分
grade += s1.warter_point if s1.warter_point else 0
list_info.append("生活配套")
# if preference[2] : # 交通 -----交通打分
# sum_list.append("IFNULL(induzone.electricity_point,0)")
if preference[2] !="false":
grade += s1.electricity_point if s1.electricity_point else 0
list_info.append("交通")
if preference[4] != "false": # 园区配套服务 ----园区的学校,商业街,宾馆打分
list_info.append("园区配套服务")
grade += s1.mall_point if s1.mall_point else 0
grade += s1.hotel_point if s1.hotel_point else 0
grade += s1.school_point if s1.school_point else 0
list_info = ",".join(list_info)
grade = grade / (0.2 * new_preference.count("true")) * 100
info = info.format(list_info, int(grade))
else:
info = "请选择选址偏好后得到更为精确定位"
data[i]["info"] = info
return jsonify(code=RET.OK, msg="选址成功", data=data)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
# 地图的处理
@api_address.route("/map", methods=["POST"])
def map():
req_dict = request.get_json()
district = req_dict.get("district")
try:
if not district:
# 获取所有的园区值
district_list = Induzone.query.filter_by().all()
data = [{"name": j.name, "jwd": {"lat": j.lat, "lng": j.lng}} for j in district_list]
return jsonify(code=RET.OK, msg="查找成功", data=data)
district_list = Induzone.query.filter_by(region=district)
data = [{"name": i.name, "jwd": {"lat": i.lat, "lng": i.lng}} for i in district_list]
return jsonify(code=RET.OK, msg="查找成功", data=data)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
# 获取行业筛选条件
@api_address.route("/downList", methods=["GET"])
def downlist():
"""一级二级行业分类"""
try:
industry = Industry.query.filter_by(statu=1).all()
data = [{
"name": i.name,
"id": i.nid,
} for i in industry]
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
return jsonify(code=RET.OK, msg="查找成功", data=data)
import copy
import pymysql
from sqlalchemy import func, desc, or_
from flask import current_app, request, jsonify
from apps.models import Induzone, Industry, CompanyIndustryPoint
from apps.utils.response_code import RET
from apps.view_choose_address import api_address
# 选址评估,选择建议
@api_address.route("/advice", methods=["POST"])
def advice():
req_dict = request.get_json()
industry = req_dict.get("industry") # 所属行业选择 nid(必填)
product = req_dict.get("product") # 主营产品 "药" (必填)
budget = req_dict.get('budget') # 落地投资预算 "22" # 大于 (必填)
preference = req_dict.get("preference") # 选址偏好 [f,f,t,f,f,f]
revenue = req_dict.get("revenue") # 去年营收 "2" (非必填)
tax = req_dict.get("tax") # 去年税收 "1" (非必填)
address = req_dict.get("address") # 意向选址 "小店区" (非必填)
# print(address)
if not all([industry, product, budget, preference]):
return jsonify(code=RET.DATAERR, msg="数据不全")
try:
indu = Industry.query.filter_by(nid=industry).first()
if not indu:
return jsonify(code=RET.DATAERR, msg="参数错误")
industry_name = indu.oname
# zone = Induzone.query.outerjoin(CompanyIndustryPoint, Induzone.name == CompanyIndustryPoint.district). \
# filter(or_(Induzone.navigat.like("%{}%".format(industry_name)),
# Induzone.navigator.like("%{}%".format(industry_name)))). \
# filter(Induzone.invest_power <= budget)
zone = Induzone.query.filter(or_(Induzone.navigat.like("%{}%".format(industry_name)),
Induzone.navigator.like("%{}%".format(industry_name)))). \
filter(Induzone.invest_power <= budget)
if address: # 选址
zone = zone.filter(or_(Induzone.region == address, Induzone.development_zone == address))
if tax: # 税收
zone = zone.filter(Induzone.tax <= tax)
if preference[0] == "true": # 政府扶持力度 --- 政策数的打分
zone = zone.order_by(Induzone.policy_point.desc())
if preference[1] == "true": # 产业聚集度 --- 产业的打分
zone = zone.outerjoin(CompanyIndustryPoint, Induzone.name == CompanyIndustryPoint.district).filter(
CompanyIndustryPoint.f_type == industry).order_by(CompanyIndustryPoint.point.desc())
# zone = zone.order_by(CompanyIndustryPoint.point.desc())
if preference[2] == "true": # 交通 -----交通打分
zone = zone.order_by(Induzone.electricity_point.desc())
if preference[3] == "true": # 生活配套 -------水电打分、最低、普工、中级人员薪资
zone = zone.order_by(Induzone.warter_point.desc()).order_by(Induzone.wagelevel.desc()).order_by(
Induzone.worker.desc()).order_by(Induzone.middlemag.desc())
if preference[4] == "true": # 园区配套服务 ----园区的学校,商业街,宾馆打分
zone = zone.order_by(Induzone.mall_point.desc(), Induzone.hotel_point.desc(), Induzone.school_point.desc())
if preference[5] == "true": # 地区经济发展 ---GDP的打分
zone = zone.order_by(Induzone.gdp_point.desc())
zone = zone.group_by(Induzone.name)
result = zone.limit(3).all()
data = [{"id": i.id,
"name": i.name,
"charge": i.charge if i.charge else "-",
"phone": i.phone if i.phone else "-",
"jwd": {"lng": i.lng, "lat": i.lat}} for i in result]
# print(data)
# 没有查询结果的查找
# if not result:
# # 在第一条建议显示
# data = [{"name": "对不起,没有找到合适的园区!"}]
new_preference = copy.deepcopy(preference)
# del new_preference[2]
for i in range(0, len(data)):
if "true" in new_preference:
grade = 0
list_info = []
info = "根据{}算出结果,得分为{}"
s1 = Induzone.query.get(data[i]["id"])
if preference[5] != "false": # 地区经济发展 ---GDP的打分
grade += s1.gdp_point if s1.gdp_point else 0
list_info.append("地区经济发展")
if preference[1] != "false": # 产业聚集度 --- 产业的打分
# sum_list.append("IFNULL(company_industry_point,0)")
ss = CompanyIndustryPoint.query.filter_by(district=data[i]["name"], f_type=industry).first()
grade += ss.point if ss else 0
list_info.append("产业聚集度")
if preference[0] != "false": # 征服扶持力度 --- 政策数的打分
grade += s1.policy_point if s1.policy_point else 0
list_info.append("政府扶持力度")
if preference[3] != "false": # 生活配套 -------水电打分
grade += s1.warter_point if s1.warter_point else 0
list_info.append("生活配套")
# if preference[2] : # 交通 -----交通打分
# sum_list.append("IFNULL(induzone.electricity_point,0)")
if preference[2] != "false":
grade += s1.electricity_point if s1.electricity_point else 0
list_info.append("交通")
if preference[4] != "false": # 园区配套服务 ----园区的学校,商业街,宾馆打分
list_info.append("园区配套服务")
grade += s1.mall_point if s1.mall_point else 0
grade += s1.hotel_point if s1.hotel_point else 0
grade += s1.school_point if s1.school_point else 0
list_info = ",".join(list_info)
grade = grade / (0.2 * new_preference.count("true")) * 100
info = info.format(list_info, int(grade))
else:
info = "请选择选址偏好后得到更为精确定位"
data[i]["info"] = info
# 没有查询结果的查找
if not result:
# 在第一条建议显示
data = [{"name": "对不起,没有找到合适的园区!"}]
return jsonify(code=RET.OK, msg="选址成功", data=data)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
# 地图的处理
@api_address.route("/map", methods=["POST"])
def map():
req_dict = request.get_json()
district = req_dict.get("district")
try:
if not district:
# 获取所有的园区值
district_list = Induzone.query.filter_by().all()
data = [{"name": j.name, "jwd": {"lat": j.lat, "lng": j.lng}} for j in district_list]
return jsonify(code=RET.OK, msg="查找成功", data=data)
district_list = Induzone.query.filter_by(region=district)
data = [{"name": i.name, "jwd": {"lat": i.lat, "lng": i.lng}} for i in district_list]
return jsonify(code=RET.OK, msg="查找成功", data=data)
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
# 获取行业筛选条件
@api_address.route("/downList", methods=["GET"])
def downlist():
"""一级二级行业分类"""
try:
industry = Industry.query.filter_by(statu=1).all()
data = [{
"name": i.name,
"id": i.nid,
} for i in industry]
except Exception as e:
current_app.logger.error(e)
return jsonify(code=RET.DBERR, msg="数据库错误")
return jsonify(code=RET.OK, msg="查找成功", data=data)
......@@ -110,7 +110,7 @@ def enterprise():
# 全国企业列表
@api_mobile.route('/attract/enterprise', methods=['POST'])
@api_mobile.route('/attract_map/enterprise', methods=['POST'])
# @login_required
def att_enterprise():
'''
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment