CptAwe

download portfolio

Jan 16th, 2019
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.78 KB | None | 0 0
  1.  
  2.     def download_portfolio(self):
  3.         '''
  4.        \r[GeoPap]
  5.        \rIt sends the appropriate query to the database
  6.        \rand fetches the answer as a file
  7.        '''
  8.  
  9.         params = request.get_json()
  10.  
  11.        
  12.         '''
  13.        input example:
  14.        {
  15.            'regions': ['China'],
  16.            'markets': ['Beijing', 'Changsha', 'Chengdu', 'Chongqing', 'Dongguan', 'Guangzhou', 'Hangzhou', 'Hong Kong', 'N/A', 'Nanjing', 'Qingdao', 'Shanghai', 'Shenyang', 'Shenzhen', 'Suzhou', 'Taipei', 'Tianjin', 'Wuhan', 'Wuxi', "Xi'an", 'Xiamen'],
  17.            'gates': ['A', 'B', 'C', 'D'],
  18.            'comparables': True
  19.        }
  20.        '''
  21.        
  22.         # remove invalid entries
  23.         params['markets'].remove("N/A")
  24.  
  25.  
  26.         columns=['score_order',
  27.                 'region',
  28.                 'stargate_market',
  29.                 'target_region',
  30.                 'target_market',
  31.                 'gate',
  32.                 'subject_property',
  33.                 'comparable_property',
  34.                 'price_1p',
  35.                 'avg_price_per_desk',
  36.                 'occupancy',
  37.                 'discount']
  38.  
  39.  
  40.  
  41.  
  42.         # Note the problematic entries
  43.         problematic=[]
  44.         for mark in params['markets']:
  45.             if "\'" in mark:
  46.                 problematic.append(mark)
  47.  
  48.  
  49.  
  50.         # print("These have invalid characters:\n%s"%(problematic))
  51.  
  52.  
  53.         regions="target_region=\'"+"\' OR target_region=\'".join(params['regions']).lstrip("OR ")+"\'"
  54.         markets="target_market=\'"+"\' OR target_market=\'".join(params['markets']).lstrip("OR ")+"\'"
  55.         gates="gate=\'"+"\' OR gate=\'".join(params['gates']).lstrip("OR ")+"\'"
  56.         comparables_bool=params['comparables']
  57.  
  58.         # Replace the problematic entries with the unproblematic ones
  59.         for word in problematic:
  60.             markets=markets.replace(word,word.replace("\'","\'\'"))
  61.  
  62.  
  63.         # The basis of the query
  64.         query='''SELECT * FROM portofolio_top5
  65.                WHERE
  66.                (%s) AND
  67.                (%s) AND
  68.                (%s)
  69.                '''%(
  70.                     regions,
  71.                     markets,
  72.                     gates)
  73.  
  74.         # if comparables_bool==True then all score_order's are selected
  75.         # otherwise only score_order==0 are selected
  76.         if comparables_bool:
  77.             query+='''AND \n\t('''
  78.             for i in range(7):
  79.                 query+='''score_order=%s OR '''%(i)
  80.             query=query[:-4]
  81.             query+=")"
  82.         else:
  83.             query+='''AND \n\t(score_order=0)'''
  84.  
  85.  
  86.         # order first by subject_property and then by score_order
  87.         query+='''\n\tORDER BY\n\t (subject_property,score_order)'''
  88.  
  89.  
  90.         # print("-----------------------")
  91.         # print("This is the query that is about to be sent:\n%s"%(query))
  92.  
  93.  
  94.  
  95.         with self.db_connector.get_db_cursor(cursor_factory=NamedTupleCursor) as cur:
  96.             cur.execute(query)
  97.             portfolio=pd.DataFrame(data=cur.fetchall())
  98.  
  99.  
  100.  
  101.         portfolio.columns=columns
  102.  
  103.  
  104.         # round up the avg_price_per_desk for those that score_order=0
  105.         rounded_prices=portfolio.loc[portfolio['score_order']==0,:].loc[:,'avg_price_per_desk'].round()
  106.  
  107.         columns.remove('avg_price_per_desk')
  108.  
  109.         portfolio.loc[portfolio['score_order']==0,:]=portfolio.loc[portfolio['score_order']==0,columns]
  110.  
  111.  
  112.         portfolio.loc[portfolio['score_order']==0,'avg_price_per_desk']=rounded_prices
  113.  
  114.  
  115.  
  116.         # Make it pretty
  117.         columns2delete=['score_order','target_region','target_market']
  118.         portfolio.drop(labels=columns2delete, axis="columns", inplace=True)
  119.  
  120.         portfolio.rename(index=str, columns={
  121.             # "score_order": "score_order",# This is deleted
  122.             "region": "Region",
  123.             "stargate_market": "Market",
  124.             # "target_region": "target_region",# This is deleted
  125.             # "target_market": "target_market",# This is deleted
  126.             "gate": "Gate",
  127.             "subject_property": "Subject Property",
  128.             "comparable_property": "Comparable Property",
  129.             "price_1p": "1P Market Price",
  130.             "avg_price_per_desk": "Avg market price (USD)",
  131.             "occupancy": "Occupancy (this mo)",
  132.             "discount": "Discount (this mo)"}, inplace=True)
  133.  
  134.         print(portfolio)
  135.  
  136.         # Download
  137.         output = BytesIO()
  138.         writer = pd.ExcelWriter(output, engine='xlsxwriter')
  139.         portfolio.to_excel(writer, sheet_name='PortfolioView')
  140.  
  141.         writer.save()
  142.         output.seek(0)
  143.  
  144.         filename="PortfolioView.xlsx"
  145.  
  146.         return send_file(output, attachment_filename=filename,as_attachment=True)
  147.  
  148.  
  149.         # avala = {'avala': 'avala_katravala_vrika_tripa_ta_vala'}
  150.  
  151.         # return json.dumps(avala)
Add Comment
Please, Sign In to add comment