I'm new to flask world and wondering what causes the program to fail. every time i run my app i'm getting interfaceError. i was able to print the data on command line but this error displayed when i'm trying to render on html. thank you so much for your help
here is my mainApp.py file
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from models import People, db
from flask_migrate import Migrate
import psycopg2
# creates an application that is named after the name of the file
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://student_user:1234#localhost:5432/studentdb"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
migrate = Migrate(app, db)
#conn = "postgresql://student_user:1234#localhost:5432/studentdb"
conn = psycopg2.connect(dbname="teacherdb", host="localhost", user="teacher_user", password=1234)
cur = conn.cursor()
#app.route('/')
def index():
# Execute a query
cur.execute("SELECT * FROM teachertb")
# Retrieve query results
records = cur.fetchall()
print(records)
conn.close()
return render_template("index.html", records=records)
if __name__ == "__main__":
app.run(debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body>
{% for record in range(0, len(records)) %}
<p>{{ records[record][1] }}</p>
{% endfor %}
</body>
</html>
Lastly, if name == "main": checks that the current file is being run as the main program and calls app.run(debug=True) to start the application with the debug mode enabled.
Please note that the configuration of the database(like user name,password,host) may have to be updated accordingly. It also seems like the connection is closed before sending the records variable to the template, which may cause the program to not work properly.
I try to navigate from list page to detail page, when i tried with the below code. I got error stating that field error. For that I've tried with adding a empty Slug field in models, it shows an page not found error.
#urls.py
from django.urls import path
from .views import (TaskListView,TaskDetailView)
app_name = 'Tasks'
urlpatterns = [
path('', TaskListView.as_view(), name='list'),
path('<slug:slug>/', TaskDetailView.as_view(), name='detail'),
]
#views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from django.views.generic import ListView, DetailView, View
from .models import Taskmanager
def home(request):
return render(request, 'home.html')
class TaskListView(ListView):
template_name = 'Tasks.html'
model = Taskmanager
context_object_name = 'data'
class TaskDetailView(DetailView):
template_name = 'detail.html'
model = Taskmanager
context_object_name = 'data'
#models.py
from django.db import models
from django.urls import reverse
# Create your models here.
week_number = (("week01", "week01"),
("week02", "week02"),
("week03", "week03"),
("week04", "week04"),
("week05", "week05"),
("week06", "week06"),
("week07", "week07"),
("week08", "week08"),
("week09", "week09"),
("week10", "week10"),
("week11", "week11"),
("week12", "week12"),
("week13", "week13"),
("week14", "week14"),
("week15", "week15"),
("week16", "week16"),
("week17", "week17"),
("week18", "week18"),
("week19", "week19"),
("week20", "week20"),
("week21", "week21"),
("week22", "week22"),
("week23", "week23"),
("week24", "week24"),
("week25", "week25"),
("week26", "week26"),
("week27", "week27"),
("week28", "week28"),
("week29", "week29"),
("week30", "week30"),
("week31", "week31"),
("week32", "week32"),
("week33", "week33"),
("week34", "week34"),
("week35", "week35"),
("week36", "week36"),
("week37", "week37"),
("week38", "week38"),
("week39", "week39"),
("week40", "week40"),
("week41", "week41"),
("week42", "week42"),
("week43", "week43"),
("week44", "week44"),
("week45", "week45"),
("week46", "week46"),
("week47", "week47"),
("week48", "week48"),
("week49", "week49"),
("week50", "week50"),
("week51", "week51"),
("week52", "week52"),
("week53", "week53"),
)
class Taskmanager(models.Model):
CurrentSprint = models.CharField(max_length=10, default="week01",
choices=week_number)
todaydate = models.DateField()
taskname = models.SlugField(max_length=200)
testrun = models.URLField(max_length=300)
comments = models.CharField(max_length=300)
assignedto = models.EmailField(max_length=70)
def __str__(self):
return self.taskname
def get_absolute_url(self):
return reverse('Tasks:detail', kwargs={'slug': self.taskname})
#Tasks.html
<a href="{% url 'Tasks:detail' slug='detail'%}"> {{Taskmanager.todaydate}}
</a>
I need an output when I click the link, it needs to navigate to the details page where the details of the task needs to be displayed.
try adding this
#views.py
class TaskDetailView(DetailView):
...
def get_object(self):
instance = get_object_or_404(Taskmanager, slug=self.kwargs['slug'])
return instance
#models.py
django.db.models.signals import pre_save
class Taskmanager(models.Model):
...
taskname = models.CharField(max_length=200)
slug = models.SlugField(max_length=100)
...
def pre_save_Taskmanager_receiver(instance, *args, **kwargs):
if not instance.slug:
instance.slug = instance.taskname
pre_save.connect(pre_save_Taskmanager_receiver, sender= Taskmanager)
# task.html
{{ data.todaydate }}
I am building simple chatting application using WebSocket using Eclipse and apache 7.x .However I am not able to compile my code cause it shows import javax.websocket cannot be resolved. After Googling a lot i found Link that shows external jar in application. I added a jar in my library section. It removed my current error but gave another. Now it showing WebSocket connection to 'ws://localhost:8080/WebSocket/socket' failed: Error during WebSocket handshake: Unexpected response code: 404
I'v tried a lot like adding servlet-api.jar to build path from apache lib. And also find some information like It provides also the javax.websocket-api-1.0.jar library so this is not needed in you application. You might need it at compile time but the server will provide it at runtime
Now I got stuck like in recursion. when I remove my jar got first error and when I add external jar then got second error. please help me in this issue cause we are developing mini project for real time collaborative editor and we are suppose to use websocket in it.
Now here is my code for websocket(not using maven):
WebSocket.java
package com.psl.service;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;
#ServerEndpoint("/socket")
public class WebSocket {
Set<Session> sessionSet = Collections.synchronizedSet(new HashSet<>());
#OnOpen
public void onOpen(Session webSession) {
System.out.println("Opened");
sessionSet.add(webSession);
}
#OnMessage
public void onMessage(String message, Session webSession) throws IOException {
System.out.println("Got message "+message);
String username = (String)webSession.getUserProperties().get("username");
if(username==null) {
webSession.getUserProperties().put("username", message);
webSession.getBasicRemote().sendText(buildJSON(username, message));
}
else {
for(Session s : sessionSet) {
s.getBasicRemote().sendText(buildJSON(username, message));
}
}
}
private String buildJSON(String string, String string2) {
String jsonData="";
JSONObject obj=new JSONObject();
try {
obj.put("message",string + ":" + string2);
StringWriter out = new StringWriter();
JSONWriter jwriter = new JSONWriter(out);
jwriter.key(string).value(string2);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#OnClose
public void onClose() {
System.out.println("CLosed");
sessionSet.remove(sessionSet);
}
}
chat.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
var websocket = new WebSocket("ws://localhost:8080/WebSocketDemo/socket");
websocket.onmessage = function onMessage(message) {
var jsonData = JSON.parse(message.data);
if(jsonData.message != null) {
messageTextArea.value += jsonData.message + "\n";
}
}
function sendMessage() {
websocket.send(sendText.value);
sendText.value = "";
}
</script>
</head>
<body>
<textarea rows="30" cols="70" id="messageTextArea" ></textarea><br /><br />
<input id="sendText">
<input type="button" value="Send" onclick="sendMessage()">
</body>
</html>
I got answer for this query. This is because the added jar overrides my internal jars in apache tomcat. And I am using older tomcat that have not websocket-api.jar
So My solution for this problem is either use glashfish 4.x or else use apache tomcat 8.x that gives us required jar to run websocket. No need to add any extra websocket api jar.
Is application.conf already loaded when the code in Global.scala is executed? I'm asking because I've tried to read some configuration items from Global.scala and I always get None. Is there any workaround?
In Java it's available beforeStart(Application app) already
public class Global extends GlobalSettings {
public void beforeStart(Application app) {
String secret = Play.application().configuration().getString("application.secret");
play.Logger.debug("Before start secret is: " + secret);
super.beforeStart(app);
}
}
As it's required to i.e. configuring DB connection, most probably Scala works the same way (can't check)
Here below is how to read the configuration just after it has been loaded but before the application actually starts:
import play.api.{Configuration, Mode}
import play.api.GlobalSettings
import java.io.File
import utils.apidocs.InfoHelper
object Global extends GlobalSettings {
override def onLoadConfig(
config: Configuration,
path: File, classloader:
ClassLoader,
mode: Mode.Mode): Configuration = {
InfoHelper.loadApiInfo(config)
config
}
}
And here below, just for your info, is the source of InfoHelper.loadApiInfo – it just loads API info for Swagger UI:
package utils.apidocs
import play.api.Configuration
import com.wordnik.swagger.config._
import com.wordnik.swagger.model._
object InfoHelper {
def loadApiInfo(config: Configuration) = {
config.getString("application.name").map { appName =>
config.getString("application.domain").map { appDomain =>
config.getString("application.emails.apiteam").map { contact =>
val apiInfo = ApiInfo(
title = s"$appName API",
description = s"""
Fantastic application that makes you smile. You can find our
more about $appName at $appDomain.
""",
termsOfServiceUrl = s"//$appDomain/terms",
contact = contact,
license = s"$appName Subscription and Services Agreement",
licenseUrl = s"//$appDomain/license"
)
ConfigFactory.config.info = Some(apiInfo)
}}}
}
}
I hope it helps.
I'm creating a form with z3c.form and for a textarea, I would like to have a wysiwyg interface.
So I use plone.directives.form to handle that.
In my interfaces.py :
from zope import schema
from plone.directives import form
from plone.app.z3cform.wysiwyg import WysiwygFieldWidget
from zope.i18nmessageid import MessageFactory
_ = MessageFactory('BSWMinisite')
class IMinisiteProperties(form.Schema):
""" """
form.widget(edito=WysiwygFieldWidget)
edito = schema.Text(title = u"Edito",
required=False)
In my content.py :
from plone.directives import form
from z3c.form import button
from Products.CMFPlone import PloneMessageFactory as plMF
from plone.z3cform.layout import wrap_form
from Products.CMFCore.utils import getToolByName
from Products.BSWMinisite.interfaces import IMinisiteProperties
class MinisitePropertiesForm(form.SchemaForm):
""" """
schema = IMinisiteProperties
ignoreContext = True # don't use context to get widget data
#button.buttonAndHandler(plMF('label_save', default=u'Save'), name='apply')
def handleApply(self, action):
""" stuff """
#button.buttonAndHandler(plMF('label_cancel', default=u'Cancel'),
name='cancel')
def handleCancel( self, action):
self.request.RESPONSE.redirect( self.context.absolute_url() )
MinisitePropertiesView = wrap_form(MinisitePropertiesForm)
And in the configure.zcml I have :
<include package="plone.directives.form" file="meta.zcml" />
<include package="plone.directives.form" />
<browser:page
for="*"
name="minisite_properties"
class=".browser.content.MinisitePropertiesView"
permission="cmf.ModifyPortalContent"
/>
When I go to ##minisite_properties I see my field, but no wysiwyg.
Do you hnow where I missed something ?
Below is my sample code for Dexterity content schema using Dexterity 1.1 pindowns (see Dexterity manual, installation part)
from five import grok
from zope import schema
from plone.directives import form, dexterity
from plone.app.z3cform.wysiwyg import WysiwygFieldWidget
class ICourseInfoContent(form.Schema):
"""
Content page for CourseInfo folders
"""
# Autofilled by course id
title = schema.TextLine(title=u"Title", required=True, default=u"")
# -*- Your Zope schema definitions here ... -*-
form.widget(body=WysiwygFieldWidget)
body = schema.Text(title=u"Body (top)")
So, the problem was I didn't have the correct version of dexterity, and my package wasn't grok'ed correctly.
In the buildout, to pin the correct dexterity :
extends =
base.cfg
versions.cfg
http://good-py.appspot.com/release/dexterity/1.1?plone=4.1.3
In the main configure.zcml :
<configure xmlns="http://namespaces.zope.org/zope"
xmlns:browser="http://namespaces.zope.org/browser"
xmlns:five="http://namespaces.zope.org/five"
xmlns:i18n="http://namespaces.zope.org/i18n"
xmlns:grok="http://namespaces.zope.org/grok"
i18n_domain="BSWMinisite">
<!-- Grok the package to initialise schema interfaces and content classes -->
<grok:grok package="." />
<browser:page
for="*"
name="minisite_properties"
class=".browser.content.MinisitePropertiesView"
permission="cmf.ModifyPortalContent"
/>
...
And then in my content.py :
from five import grok
class MinisitePropertiesForm(form.SchemaForm):
""" """
grok.context(IMinisiteProperties)
schema = IMinisiteProperties