I'm using python, flask, sqlalchemy/sqllite, jinja for my workflow.
I have a HEAP of text stored in the database and it's got paragraphs of plain text and in that text will be things like email#address.com, somedomain.com, www.somedomain.com, https://somedomain.com, https://www.somedomain.com, etc etc.
Is there a solution that exists for parsing the data as I load it and rendering it out as html links when I draw to the browser? Currently it just renders as text without links being active.
Thanks so much
A quick solution would be to use an existing library, python-textile, built for such a task.
For example:
import textile
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def index():
plain_text = 'This text contains a link to https://stackoverflow.com'
marked_up_text = textile.textile(plain_text)
return render_template('layout.html', body=marked_up_text)
layout.html
{{body | safe}}
Related
I want to deploy a web map apps which containing several points and Plotly graphs as folium popup. Everything is fine until I want to deploy my web map apps in Flask, which when I click the point, the pop up shows error message says
The requested URL was not found on the server. If you entered the URL
manually please check your spelling and try again.
Here is the popup code
#make a dataframe which is used for plotting the well head point in folium
df_point = pd.DataFrame(list(zip(wells, html_list, Longitude, Latitude)), columns =['Well_Name', 'HTML_list', 'Longitude', 'Latitude'])
#Start plotting well head in map with well log plot as a pop up widget
for i in range(0,len(df_point)):
html="""
<iframe src=\"""" + df_point['HTML_list'][i] + """\" width="700" height="800" frameborder="0">
""")
popup = folium.Popup(folium.Html(html, script=True))
# #Cirlce marker ver.
# folium.CircleMarker([df_point['Latitude'].iloc[i],df_point['Longitude'].iloc[i]],
# popup=popup,radius=3.5,opacity=1,color='#ccd132').add_to(map1)
#Marker with icon ver.
folium.Marker([df_point['Latitude'].iloc[i],df_point['Longitude'].iloc[i]],
popup=popup,icon=folium.Icon( icon='glyphicon-pushpin')).add_to(map1)
I put the HTML file, coordinate and name on dataframe which is called df_point, here is the dataframes
Well_Name HTML_list Longitude Latitude
0 Well 1F figWell 1F.html 96.083956 5.456862
1 Well 2F figWell 2F.html 96.356427 5.328133
and here is my Flask app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def render_the_map():
return render_template('testing_map.html')
if __name__ == '__main__':
app.run(debug=True)
and also here is the path if someone need my file path information
How do I put the Plotly graphs in HTML format as pop up folium on Flask? I'm still new in Flask development. Any help I would appreciate it, Thanks!
I found a solution based on Sebastian's answer, if someone want to make a Folium map and the pop up marker showing plotly html in Flask, here's how to do it
first, in the app.py, make a route for the plotly plot
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def render_the_map():
return render_template('testing_map.html')
#app.route('/figure1')
def figure_plotly1():
return render_template('figWell 1F.html')
#app.route('/figure2')
def figure_plotly2():
return render_template('figWell 2F.html')
if __name__ == '__main__':
app.run(debug=True)
and then, search your plotly code in your folium map html and change the iframe source to the defined route, so for example, my plotly html graph name is figWell 1F.html, try to ctrl+F in your main HTML folium map and change the iframe src to be like this
<iframe src="{{url_for('figure_plotly1')}}" width="700" height="800"
and it works like a charm
I have a login page for a flask app with cloud database, I want to test the results after logging in, specifically, I want to test the HTML elements after logging in. I have seen people test return status code or using assertIn to check if data exist.
Is there a way for me to target a specific HTML tag, like <h1 id="userTitle"> </h1> from rendered templates after POST username, password to the route function login()
def test_users_login(self):
result = self.app.post('/login', data=dict(username='Nicole', password='abc123'), follow_redirects=True)
# I want to check the HTML tag's text value data after logging in
self.assertEqual(result.data.getTag("h1", b"Nicole") #What I imagined using <h1>
self.assertEqual(result.data.getId("user", b"Nicole") #What I imagined using id
#This returns true which is okay, because 'Nicole' exists in the whole page
self.assertIn(b'Nicole', result.data)
In my rendered jinja2 template I have this which is after logging in.
<h1 id="userTitle">{{ session['username'] }},Welcome!</h1>
I guess assertIn works well, but I just want to know how to test an HTML tag without running a browser test.
Although I didn't get a correct answer from here, but I just managed to do the unit-test with just assertIn, by checking the contents of the page.
Thanks everyone
In one of the requirement, I need to integrate Google Map with Dash framework and on map click - retrieve lat , long and address (on map click event).
I was able to retrieve the same using google API and flask framework using java script which gives Lat ,Long and Address based on map click event and renders Google Map
Here is the python code used in flask framework :
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/map', methods=['GET', 'POST'])
def map():
location = {}
if request.method == "POST":
location = request.get_json()
# latitude = location['latitude']
# longitude = location['longitude']
print(location);
return render_template('map.html')
if __name__ == '__main__':
app.run(debug = True) # run app
Any guidance how to achieve the same using Dash Framework would be really helpful. I can share JS Script Code as well if needed.
You could use Dash Leaflet for the map visualization. It supports arbitrary tile provides, i.e. also Google, as well as click events. You would need another library for the reverse geocoding though, one options is Googles API.
Disclaimer: I am the maintainer of Dash Leaflet.
I'm working on some code that pulls course info from Canvas. As pure python, it works fine. If I try to incorporate it with Flask, I get the following error
requests.exceptions.MissingSchema: Invalid URL 'run/api/v1/courses/1234567': No schema supplied. Perhaps you meant http://run/api/v1/courses/1234567?
This is the code in question:
Canvas file
import sys
from canvasapi import Canvas
def getinfo():
canvasurl = "https://canvas.instructure.com/";
canvastoken = #Redacted for this example
try:
canvastoken = sys.argv[1];
canvasurl = sys.argv[2];
except:
print()
#Create a new canvas object passing in the newly aquired url and token
canvas = Canvas(canvasurl, canvastoken);
#print(canv)
# Create a new course oject -- passing in course number as a parameter
# Course number is currently hard coded
print(canvas.get_course(1234567))
Flask file code (the file that I'm trying to run):
from flask import Flask
import canvas
canvas.getinfo()
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
No schema provided usually means you haven't specified the http:// or https:// in the URL.
In the code you provided, I don't see any reference to a run/api/v1/courses/1234567. One possibility is if you are using the url_for method from requests anywhere in your code, try setting _external=True:
url = url_for('relativeURL', _external=True)
This allows Flask to construct an absolute URL (i.e., a URL with domain included).
If you aren't using url_for, check other places in your code where you might be omitting the http or https from the URL.
If you update your question to include the part that refers to the offending URL, we might be able to provide more specific help.
I'm using Flask-Misaka with Flask to render a markdown string to html. However, it seems that the Flask-Misaka can't recognize fenced code. It does removed the back-ticks, but no colored block is displayed. I have tried with versions 0.4.0 and 0.4.1.
app.py
from flask import Flask, render_template
from flask_misaka import Misaka, markdown
app = Flask(__name__)
Misaka(app, fenced_code=True)
TEST_MD = markdown("```block```\n", fenced_code=True)
#app.route("/", methods=['GET'])
def index():
return render_template('{{s|markdown}}', s=TEST_MD)
The issue is that you are missing a stylesheet. If you look at the HTML output of Flask it will show <p><code>block</code></p>\n. So the fenced code is seen and the HTML output is rendered correctly.
Short example which directly shows the result when the code is executed:
from flask import Flask, render_template_string
from flask_misaka import markdown
app = Flask(__name__)
with app.app_context():
render_template_string('{{s}}', s=markdown("```block```\n", fenced_code=True))