#HTTPServer
Explore tagged Tumblr posts
codingprolab · 2 months ago
Text
SOEN 387 Assignment-I
Servlet Hello World Objectives Understanding HttpServer, servlets, request and response objects, headers, content-types, and encoding. Project Outline In this assignment, you are asked to create a web project containing static html pages, a dynamic servlet, and an additional http server. The following directory structure outlines the web project: +your_app_root +WEB-INF/……
0 notes
jinxypoodle · 3 months ago
Text
Ip address: 127.0.0.1:8000 Nightspace Chat
import socket from http.server import HTTPServer, BaseHTTPRequestHandler import argparse import threading import webbrowser import urllib.parse
class HTMLHandler(BaseHTTPRequestHandler): """Handles HTTP requests and serves HTML from input."""def do_GET(self): """Handles GET requests.""" if self.path.startswith('/'): if '?' in self.path: query = urllib.parse.urlsplit(self.path).query query_components = urllib.parse.parse_qs(query) if 'myTextbox' in query_components: text_input = query_components['myTextbox'][0] self.server.messages.append(text_input) # Add message to the list print(f"Text box input: {text_input}") self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() message_list_html = "".join([f"<p>{msg}</p>" for msg in reversed(self.server.messages)]) #reversed to show most recent first. html_with_textbox = self.server.html_content + f""" <br><br> <form action="/" method="GET"> <input type="text" id="myTextbox" name="myTextbox" placeholder="Type here..."> <input type="submit" value="Submit"> </form> <br> {message_list_html} """ self.wfile.write(html_with_textbox.encode('utf-8')) else: self.send_response(404) self.end_headers()
def run_server(ip_address, port, html_content): """Starts an HTTP server with dynamic HTML content.""" try: server = HTTPServer((ip_address, port), HTMLHandler) server.html_content = html_content server.messages = [] # Initialize message list print(f"Serving dynamic HTML on http://{ip_address}:{port}") server.serve_forever() except OSError as e: if e.errno == 98: print(f"Error: Address {ip_address}:{port} is already in use.") else: print(f"An unexpected Error occurred: {e}") except KeyboardInterrupt: print("\nStopping server…") server.shutdown() print("Server stopped.")
if name == "main": parser = argparse.ArgumentParser(description="Serve dynamic HTML from input.") parser.add_argument("-p", "--port", type=int, default=8000, help="Port number to listen on.") parser.add_argument("-i", "--ip", type=str, default="127.0.0.1", help="IP address to listen on.") parser.add_argument("-o", "--open", action="store_true", help="Open the webpage in a browser automatically.") parser.add_argument("-f", "--file", type=str, help="Read HTML content from a file.") parser.add_argument("html_content", nargs="*", help="HTML content to serve (as command-line arguments).")args = parser.parse_args() html_content = "" if args.file: try: with open(args.file, 'r') as f: html_content = f.read() except FileNotFoundError: print(f"Error: File '{args.file}' not found.") exit(1) elif args.html_content: html_content = " ".join(args.html_content) else: html_content = input("Enter HTML content: ") server_thread = threading.Thread(target=run_server, args=(args.ip, args.port, html_content)) server_thread.daemon = True server_thread.start() if args.open: webbrowser.open(f"http://{args.ip}:{args.port}") server_thread.join()
0 notes
tinchicus · 1 year ago
Text
Node.js / frameworks web
Hoy vveremos muy teoricaamente que es un framework web, espero les sea de utilidad y buen finde!
Bienvenidos sean a este post, hoy hablaremos un poco de teoria sobre esto. Hasta ahora hemos hablado sobre el objeto HTTPServer pero este trabaja muy cerca del protocolo HTTP y si bien manejarnos a tan bajo nivel esta bien para trabajar con programacion de aplicaciones web siempre es mejor hacerlo a alto nivel, acaso alguien usa Assembler para crear paginas web? por esta razon es mejor ocultar…
Tumblr media
View On WordPress
0 notes
reconshell · 3 years ago
Link
0 notes
geekscripts · 4 years ago
Photo
Tumblr media
HTTPUploadExfil: HTTP Server for Exfiltrating Files/Data | #DataExfiltration #HTTPServer #Pentesting #Hacking
0 notes
jacardano · 8 years ago
Text
Basic Node for the Internet of Sex Toys - part 3: software
Coding the #ESP8266 driven internet of sex toy node #sextech #DIY #Arduino
Tumblr media
This the third part of the tutorial which has the following parts:
part 1: Basic Node for the Internet of Sex Toys
part 2: Molding the Basic Node
part 3: Software for the Basic Node
For the basic node a simple software realizes all features like Mqtt communication, Web server, basic web user interface, reading data from the accelerometer. Please use the code at github and send request over…
View On WordPress
0 notes
mediba-ce · 6 years ago
Text
Node.js(Express) サーバ運用と ELB タイムアウト
この記事は Node.js Advent Calendar 2019、15 日目の記事です。
こんにちは。ものづくり推進部の武田(@tkdn)です。
先日 11/30, 12/1 に弊社がスポンサードさせていただいた JSConf.jp に参加してきました。当日参加したセッションの雑多なメモはパブリックに残し、社内のコンフルには整理したものを展開し知見を持ち帰って実務にいかそうと思います。
会場廊下では、お世話になった方、知り合いのエンジニア、発表された方と立ち話する機会もありまして、情報交換や普段オンラインでのみやりとりしている方ともオフラインでコミュニケーションできて非常に充実したカンファレンスでした。
初日にスポンサートークの枠で 5 分程度ですが、mediba での フロントエンド, JavaScript についてお話させていただきました。表面的なことばかりだったのでもう少し泥臭い話もすればよかったかなと感じています(こういうのとか、こういうのとか)。
日本での初開催に向けて尽力された運営の皆さま、本当にありがとうございます。
スポンサートーク: mediba におけるフロントエンド, JavaScript
当日参加セッションメモ: JSConf.jp 雑まとめ
さて本題の記事ですが、今年度から Node.js でのサーバ運用をはじめてつまづきのあった、ロードバランサーと Express そのタイムアウト、ランタイムバージョンアップ後の問題、そして問題に対する課題感について書いています。
Node.js(Express) サーバ運用が始まる
2019 年 3 月に実施した au Webポータルのリニューアルには Next.js を利用していますが、もちろんそこには Express の存在も要るわけで、それに伴う新しい運用が始まるということでもあります。
正直なところ Node.js のサーバ運用経験があるメンバーが豊富にいたわけではな��ので、負荷試験・性能試験等で安全はもちろん担保の上で、運用に乗ってからいろいろ粗(というと言い方はよくないですが)は出るだろうなと思っていました。
ELB, Express のタイムアウトはきちんと確認しよう
au Webポータルの現アーキテクチャは CDN, AWS を利用しておりリクエストを受ける前段は
Akamai CDN -> ELB -> ECS クラスタ(Node.js コンテナ)
という形なのですが、リリース後すぐに Datadog のアラートとログから、極稀に ELB が 504 を返すことがあるということが分かりました。全体の1パーセントに満たないログです。
504 だとユーザ面に影響があるのではというツッコミが入りそうですが、最前段にある Akamai でオリジンが 5xx のステータスコードを返却する場合には正常時の stale cache を返却する構成になっているため、ユーザ面への影響はありません。ありませんが、これはこれで問題です。
504 を返していた原因としては Express 側の keepAliveTimeout を ELB に合わせたものにしていなかったというのが原因になります。リリース前に気付くべきことなのかも知れませんが、この問題については性能試験においても検出はされておらず、運用に乗せてから検出されたケースになります。
解決方法としては、ELB のアイドルタイムアウトのデフォ値が 60 秒なので、express 側は 60 秒以上にしておくといいかもしれません。
const app = express(); const httpServer = app.listen(3000, () => console.log('Example app listening on port 3000!')); /** @note タイムアウトの設定 */ httpServer.keepAliveTimeout = 70000;
参考: HTTP | Node.js v12.13.1 Documentation(デフォルト値は 5000 となっています)
Node.js v8.x -> v10.x バージョンアップ
Node.js v8 の EOL は年内(2019-12-31)となっていますが、皆さんきちんとアップデートできていますか?
弊チームはギリギリでバタバタとやりたくなかったため、au Webポータルチームが抱えているプロジェクト群(一つではありません)で利用している Lambda の Node.js ランタイムを v10 へ移行するところから始めました。割と早い段階でランタイムアップデートを行うに至った経緯としては、Lambda ランタイムの AMI が更新 というアナウンスがあったため、同時に確認し追ってかかる運用コストを減らそうという意図もありました。
アップデートによるパッケージの影響や動作確認などを終え、Lambda AMI 変更・ランタイムバージョンアップはいくつか課題があったものの解消し 7 月段階で全て v10 に切り替えを完了しています。
その後 8月に Express を運用しているコンテナ内のランタイムアップデートへと作業を進めたのですが、Node.js のバージョンアップはアプリが依存するパッケージも多く影響範囲の調査だけで相当時間がかかります。そのため、ローカル環境コンテナ内ランタイムバージョンアップ、ステージング環境へのデプロイなどで実動作から確認するのが一番手っ取り早く、動作確認とステージング環境からのアラートがないことを確認し、バージョンアップ後の担保としました。
JavaScript = Node.js はブラウザのランタイムとしてスタートしている言語であること、Chrome に搭載されている V8 をエンジンとしていること、などから後方互換性がある程度保ったままメジャーバージョンが上がっていきます。そして偶数バージョンが LTS のリリースラインにあり、奇数はすぐ EOL をむかえるリリースプロセスになっています。
バージョンアップリリース後にタイムアウト再発
実働しているコンテナのランタイムバージョンアップのリリース後、見覚えのあるアラートが上がるようになりました。
前述の ELB タイムアウト問題の再発です。
この時も数パーセントのかなり低い割合で現象が発生していました。おそらく同様の問題であるような気がしていたのですが、いろいろ調べたところ下記の記事にあたり大変助かりました。
Check Your server.keepAliveTimeout - Shuhei Kagawa
Regression issue with keep alive connections · Issue #27363 · nodejs/node · GitHub
記事にある内容は前述のロードバランサーのタイムアウトと Exress のタイムアウト見直しと同じになりますが、末尾に重要な情報とリンクがあり、二つ目の issue に詳細が書かれています。
結果から言うと v10.15.2 以上の場合は server.headersTimeout の指定を上記の keepAliveTimeout で指定した数値より大きくする必要があります(指定がない場合、デフォルト値は 40000 です)。
const app = express(); const httpServer = app.listen(3000, () => console.log('Example app listening on port 3000!')); /** @note タイムアウトの設定 */ httpServer.keepAliveTimeout = 70000; httpServer.headersTimeout = 80000;
該当の issue で話されている内容ではありますが、Slowloris HTTP DoS 攻撃(不完全なヘッダーを送り続けてサーバのプロセスを圧迫するような攻撃です)に対する防止策のコミット 1a7302b から変更があるようです。
今回の件から見えてくる課題
運用の知見がなかったものは蓄積する他ありませんが、今回その中でも課題と感じることが出てきました。
バージョンアップの担保とは
環境差異による再現性の低さ
ひとつめ、バージョンアップについてです。これは EOL がついてまわる言語を扱う以上向かい合わなくてはいけませんし、どこで安全性を担保するのか難しいところです。アップデートにより obsolute された API 等は調査で知り得るものの、既存で存在しユースケースの中で発生しえる現象については実働で確認するしかありません。
担保できる機能テストの自動化やステータスチェック等考えられることは多くありますが、何年も保持できる LTS バージョンはなく、比較的早いリリースサイクルに対してどう向き合うかは課題だと感じます。
ふたつめ、環境差異による再現性について。こちらについては、ステージング環境でタイムアウトの現象を検出できなかった点が課題と感じています。今段階でも再現せよというお題に明確な解答が出せていません。プロダクション環境で稀に出たアラートだったというところで片付けてもいいのかも知れませんがなんだかモヤります。
具体的な回避策については記述したとおりではあるものの、あまり決定的な解がなくもんやりしつつ、以上 ELB のアイドルタイムアウトと Express(Node.js)サーバのタイムアウトについて武田が書きました。
mediba ではエンジニアだけでなく一緒にプロダクトを良くしていくメンバーを募集中です。特に TypeScript でサーバサイドを書ける方や React に取り組みたい方がいらっしゃるとわたしが一方的に嬉しいのでぜひよろしくお願いいたします。
1 note · View note
techtechinfo · 3 years ago
Text
How to use Socket for realtime chat application in Node Js
Tumblr media
What is node js?
Node js is not a language. It is an environment that is open source, cross-platform, and  back-end JavaScript runtime environment that runs on the V8 javascript Engine Developed by Google chrome.  What node js can do? Node.js can create, open, read, write, delete, and close files on the server Node.js can add, modify, and delete data in your database Node.js can generate the dynamic page content Node.js can collect form data
What is WebSocket or socket.io?
the socket is a bidirectional connection between the client and server. It is a continuous connection between the server and client until any of the ones have not terminated the connection. It uses the full-duplex protocol. When we can use a web socket? Real-time web application:  in real time chat application we need to show the live data on the website or application without loading the page from the client end. Gaming application: In a Gaming application, you can see that data is continuously received by the server, and without refreshing the UI Chat application: for real-time chat applications between one-to-one users or one-to-many users    How to install web socket in node js application. Step 1: you should have installed the node js on your computer and created a base project of node js  Step 2: run the command in the terminal npm i socket.io step 3: after creating the HTTP server listen to line past the below code in your app.js your group joining request is created and a message emit request is created. httpServer.listen(3001); const io = require('socket.io')(httpServer, { allowEIO3: true,     cors: {          origin: true,          credentials: true      }, }); io.on("connection", async (socket) => { var MyRoomId = "myroomid"          socket.on("joinGroup", async (data) => {                                     await socket.join(MyRoomId);                     console.log(“user successfully connected with room”);         });   socket.on("sendMessage", async (data) => {                   await io.in(MyRoomId).emit("sendMessage_response",  {                    "error": "false",                      "message": "Message Received successfully",                     "chat": data.message                 });              return;         }); }); Now let's understand the code line by line. Const io holds the reference of socket connection. Which created the socket connection later. io.on("connection", async (socket)  After creating the connection we have created an API by which the user will join the group. and Both the users can broadcast their messages from both ends.  socket.on("joinGroup", async (data) After joining the request we need to create another request that will send the message to the group  socket.on("sendMessage", async (data) Now we need to emit the user message in the group so other users can easily read the message that is emitted by other users in the group.  await io.in(MyRoomId).emit("sendMessage_response",  {                    "error": "false",                      "message": "Message Received successfully",                     "chat": data.message                 }); Here we have emitted the JSON in myRoomid  And the listener of the message is the sendMessage_response listener. 
Tumblr media
How to run socket on postman Read the full article
0 notes
swarnalata31techiio · 3 years ago
Text
Using Python to run a HTTP server
Python:-
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of maintenance program.
Python HTTP Server
Python comes with a built-in module known as SimpleHTTPServer, which in other words is a simple HTTP server that gives you standard GET and HEAD request handlers. This module can turn any directory of your system into a web server.Example of Python HTTP ServerGiven below is the example of a Python HTTP Server:Let's create a basic HTTP web server:
Code:
from http.server import HTTPServer, BaseHTTPRequestHandler
class CustomHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('content-type','text/html')
self.end_headers()
self.wfile.write('Python HTTP Webserver Tutorial'.encode())
def main():
PRT = 8000
srv = HTTPServer(('',PRT), CustomHandler)
print('Server started on port %s' %PRT)
srv.serve_forever()
if __name__ == '__main__':
main()
Output:
The server started on port 8000127.0.0.1 – – [28/May/2020 20:36:48] “GET / HTTP/1.1” 200 –127.0.0.1 – – [28/May/2020 20:36:48] “GET /favicon.ico HTTP/1.1” 200 –
0 notes
zarinfam · 4 years ago
Text
Write concurrent programs using Isolate and Future in Dart
4 different implementations of a simple web server using Isolate and Future
We are gonna implement 4 different versions of a simple web server using the HttpServer class in the dart code library (dart:io and dart:isolate)
Read more…
Tumblr media
0 notes
tak4hir0 · 6 years ago
Link
The ultimate security is your understanding of reality. – H. Stanley Judd This article will introduce the basics of Python HTTP programming. So far in this series, we have discussed Python security programming and Python network programming. In this article the reader will learn how to implement advanced Python HTTP-related scenarios and use cases.  A web server is a computer server which stores content related to the web.  Websites are hosted on this type of server. Web servers are used for other purposes such as FTP, email, gaming, storage and more. Server is typically a term used for hardware and software. Hardware based web servers handle HTML pages, images, style sheets, javascript, and web server software. The server can handle data exchange with devices connected to the internet. Web server software consists of user management, user access, and a server based on HTTP protocol. HTTP based servers can parse URLs which are web addresses. HTTP is the protocol used for browsing and rendering web content. Web sites are browsed by searching through domain names of the web servers. The web servers store web content and have domain names configured for the network DNS ip address. A website has a group of web pages serving images, videos and audio content. An HTTP request is created by the browser to request web content on the web server. The web server returns the HTTP response by sharing the requested content with the URL. The response is generated by invoking a server side component which interacts with the database. A web server is called static if the content is shared as it is available on the server. The examples are images, videos and audio files. On the other hand, a dynamic web server has a static module and a dynamic module rendering the response from the server side components. The architectural approaches used for a web server are concurrent and single process event driven architectural patterns. A concurrent approach can process many HTTP requests simultaneously. This can be achieved by web servers with multiple threads, processes, and hybrid approaches of processes and threads. A simple web server creates a single thread. The single thread spawns multiple child processes for HTTP requests. The child processes handle the HTTP requests for further processing required for rendering the response. Multiple Processed based web servers have a master slave pattern based implementation. In this implementation, the master process manages the load by having child processes forked. Multiple Thread based servers manage multiple threads to handle concurrent requests. The hybrid approach is to have multiple processes created and threads being spawned by each process. The diagram below shows the request and response mechanism implemented in the web server.  Web Server Architecture The web server listens to HTTP requests on a TCP IP Address and a port number. It responds to the HTTP request by sending the HTTP response. The HTTP headers have the source and destination information for requests and responses. A web server is yet another network server which can handle requests and responses. The web server acts as a request dispatcher and handlers are provided to render the response. The code samples below show advanced Python HTTP scenario implementation. In this implementation, we look at the basic example in which Python is used for an HTTP web server. Prerequisites: 1. You need to set up Python3.5 to run the code samples below. You can download from this link. Problem Http.server and socket server module has the features to create a TCP server and handling of HTTPRequests. The features related to HTTPServer implementation and client connection are shown in the example below.  The code snippet below shows the Python web server using HTTP API. import http.server import socketserver HTTPPORT = 8000 HTTPRequestHandler = http.server.SimpleHTTPRequestHandler with socketserver.TCPServer(("", HTTPPORT), HTTPRequestHandler) as httpd: print("web server started", HTTPPORT) httpd.serve_forever() HTTPRequestHandler of http.server module  is used to handle the requests and serve the files from the directory of the web server. TCPServer of socket server module is used to create an HTTP web server httpd. This server receives and sends httprequests and httpresponses respectively using TCP protocol. HTTP is a TCP protocol. It is an application layer protocol. The web server is instantiated with an IP address and port number. The handler is passed, which is a Simple HTTPRequestHandler. serve_forever method is on httpd. This method is used to start the web server. The web server receives the requests  and sends the responses which are HTTP protocol messages. HTTP webserver is started by executing the commands shown below. Instructions for Running the Code #running the python web server python3 web_server.py Output Further in this series, we are going to cover network traffic analysis, information gathering from servers, FTP, SSH & SNMP interaction, cryptography, nmap scanning, geolocation & metadata retrieval, and  vulnerability scanning and analysis. The post Python Networking : HTTP Programming appeared first on Topcoder.
0 notes
jinxypoodle · 3 months ago
Text
Here is the python code for an ip address html dirrect message box to a server console message! :
import socket from http.server import HTTPServer, BaseHTTPRequestHandler import argparse import threading import webbrowser import urllib.parse
class HTMLHandler(BaseHTTPRequestHandler): """Handles HTTP requests and serves HTML from input."""def do_GET(self): """Handles GET requests.""" if self.path.startswith('/'): if '?' in self.path: query = urllib.parse.urlsplit(self.path).query query_components = urllib.parse.parse_qs(query) if 'myTextbox' in query_components: text_input = query_components['myTextbox'][0] print(f"Text box input: {text_input}") # Print to console self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() html_with_textbox = self.server.html_content + """ <br><br> <form action="/" method="GET"> <input type="text" id="myTextbox" name="myTextbox" placeholder="Type here..."> <input type="submit" value="Submit"> </form> """ self.wfile.write(html_with_textbox.encode('utf-8')) else: self.send_response(404) self.end_headers()
def run_server(ip_address, port, html_content): """Starts an HTTP server with dynamic HTML content.""" try: server = HTTPServer((ip_address, port), HTMLHandler) server.html_content = html_content print(f"Serving dynamic HTML on http://{ip_address}:{port}") server.serve_forever() except OSError as e: if e.errno == 98: print(f"Error: Address {ip_address}:{port} is already in use.") else: print(f"An unexpected Error occurred: {e}") except KeyboardInterrupt: print("\nStopping server…") server.shutdown() print("Server stopped.")
if name == "main": parser = argparse.ArgumentParser(description="Serve dynamic HTML from input.") parser.add_argument("-p", "--port", type=int, default=8000, help="Port number to listen on.") parser.add_argument("-i", "--ip", type=str, default="127.0.0.1", help="IP address to listen on.") parser.add_argument("-o", "--open", action="store_true", help="Open the webpage in a browser automatically.") parser.add_argument("-f", "--file", type=str, help="Read HTML content from a file.") parser.add_argument("html_content", nargs="*", help="HTML content to serve (as command-line arguments).")args = parser.parse_args() html_content = "" if args.file: try: with open(args.file, 'r') as f: html_content = f.read() except FileNotFoundError: print(f"Error: File '{args.file}' not found.") exit(1) elif args.html_content: html_content = " ".join(args.html_content) else: html_content = input("Enter HTML content: ") server_thread = threading.Thread(target=run_server, args=(args.ip, args.port, html_content)) server_thread.daemon = True server_thread.start() if args.open: webbrowser.open(f"http://{args.ip}:{args.port}") server_thread.join()
0 notes
tinchicus · 1 year ago
Text
Node.js / HTTP sniffer
Hoy crearemos un sniffer para HTTPServer pero en realidad es mas bien pensado como un ejemplo para entender el concepto de captura de eventos, espero le sea de utilidad!
Bienvenidos sean a este post, hoy veremos como escuchar la conversacion HTTP. En este post vimos como es el objeto HTTPServer y como utilizarlo en conjunto con EventEmitter para crear un servidor que permite la entrega de aplicaciones web, en e post de hoy veremos como crear un modulo que nos permitira escuchar a todos los eventos del objeto y se puede convertir en una herramienta muy util para…
Tumblr media
View On WordPress
0 notes
webdesignersolutions · 6 years ago
Link
So I’m trying to access my server through the graphql-playground (which worked fine in production), but when I deployed to heroku, I get a 400 error. This is my server code:
const { ApolloServer } = require('apollo-server-express') const expressPlayground = require('graphql-playground-middleware-express').default const express = require('express') const path = require('path') const session = require('express-session') const { readFileSync } = require('fs') const { createServer } = require('http') const { MongoClient } = require('mongodb') const MongoDBStore = require('connect-mongodb-session')(session) require('dotenv').config() const typeDefs = readFileSync('./typeDefs.graphql', 'UTF-8') const resolvers = require('./resolvers') async function start() { const app = express() var store = new MongoDBStore({       uri: process.env.MONGO_SESSION_STORAGE,       collection: 'mySessions' }) store.on('error', function(error) { console.log(error)    }) app.use( session({          secret: process.env.SESSION_SECRET,          resave: false,          cookie: {             maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week          },          store: store,          saveUninitialized: false       }) ) const MONGO_DB = process.env.DB_HOST const client = await MongoClient.connect(MONGO_DB, { useNewUrlParser: true }) const db = client.db() const context = async ({ req, connection, res }) => { let users = db.collection('users') let studentData = db.collection('studentData') let lessonData = db.collection('lessonData') let token let currentUser       return { users, currentUser, studentData, lessonData, db, req } } const server = new ApolloServer({ typeDefs, resolvers, context,       engine: {          apiKey: process.env.ENGINE_API_KEY } }) server.applyMiddleware({ app    }) app.get('/', (req, res) => res.end(\Teacher’s Aide API`)) app.get(‘/playground’, expressPlayground({ endpoint: ‘/graphql’ })) const httpServer = createServer(app) server.installSubscriptionHandlers(httpServer) httpServer.listen({ port: process.env.PORT || 4000 }), () => { console.log(`
Tumblr media
Server ready at ${url}`)       } } start()`
What is my problem? The ‘/’ route works, but ‘/playground’ doesn’t.
Submitted August 03, 2019 at 06:29AM by rob_moose https://www.reddit.com/r/webhosting/comments/clirjt/deploying_an_apolloserver_to_heroku_problems/?utm_source=ifttt
from Blogger http://webdesignersolutions1.blogspot.com/2019/08/deploying-apollo-server-to-heroku.html via IFTTT
0 notes
ryadel · 6 years ago
Text
Getting Started with Phyton and Django - Hello World Web App
Tumblr media
Have you ever heard anything about Phyton? If you're reading this, I bet you do! Python is an interpreted, high-level, general-purpose programming language with an object-oriented approach: it was created by Guido van Rossum in 1991 and constantly updated ever since. It's dynamically typed and supports multiple programming paradigms, including procedural, object-oriented, and functional programming. Phyton went through two major upgrades: the first in 2000, with the release of the 2.0 version, which introduced a garbage collection system capable of collecting reference cycles; the second in 2008 with the release of Python 3.0, which was a major revision - mostly backward-incompatible - of the language. Following the Phyton 3.0 release, most developers chose to stick to the 2.x version, which eventually led to extended support for Python 2.7 (the last release in the 2.x series) up to 2020. As of today, all the main resources for Phyton and CPython (an open-source implementation of Phyton) are maintained and managed by the Phyton Software Foundation, a non-profit organization.
Phyton 2 vs Phyton 3
Python 2 and Phyton 3 are the two major versions of Phyton that are still used nowadays. These two versions are quite different: although Phyton 3 arguably has a better syntax, is more semantically correct and supports newer features, most developers chose to stick with Phyton 2 until recent years thanks to a much wider database of libraries and resources available on the web. Although there still is a bit of a debate in the coding community about which Python version was the best one to learn nowadays (Python 2.7 vs 3.5), there is now a general consensus on considering Phyton 3 the most appropriate choice for newcomers and also for those who want to update their coding skills. For this very reason, in this quick tutorial, we're going to use the Phyton 3 syntax.
Console, Desktop, or Web?
Just like most programming languages, such as Java, C# and so on, Phyton can be used for a number of different purposes. The most common scenarios are: Console Applications: console applications are programs designed to be used via a text-only computer interface, such as a text terminal, the command line interface of some operating systems (Unix, DOS, etc.). Common examples include openssl, ping, telnet, defrag, chkdsk, and the likes. Desktop Applications: desktop applications are programs designed to be used via a Graphical User Interface (GUI): such GUI can either be designed by making use of the operating system native libraries or made from scratch using the language native elements (or specifically designed GUI frameworks). Typical examples of desktop applications include Photoshop, Thunderbird, Chrome, and so on. Desktop application development dominated the software world for many years and are still widely used, even if the broadband + Internet combo is making web-based applications more appealing year after year. Web Applications: web applications or web apps are client-server computer programs where the client - including the user interface (UI) and the client-side logic - runs in a web browser: common examples include webmail (such as GMail), e-banking websites, and so on. On a more general basis, we could say that most interactive websites can be defined as web applications, from the CMS who can help you to write an essay on time management to more complex, fully packaged products such as Wordpress and Joomla. In this tutorial, for the sake of simplicity, we'll talk about the latter: therefore, our Hello World sample will be a (minimal) Web Application.
Phyton Web Frameworks
The first thing you have to do before starting is to pick a decent Phyton Web Frameworks: although you can write Phyton using any text editor (including Notepad), you should definitely stick with a GUI framework to benefit from very useful features such as syntax highlighting, built-in compiler/debugger, folder tree lists, windows tiling, and so on. These are the most popular high-level web frameworks for Phyton available nowadays. Django The Web framework for perfectionists (with deadlines). Django makes it easier to build better Web apps more quickly and with less code. Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It lets you build high-performing, elegant Web applications quickly. Django focuses on automating as much as possible and adhering to the DRY (Don't Repeat Yourself) principle. TurboGears The rapid Web development web framework you've been looking for. Combines SQLAlchemy (Model) or Ming (MongoDB Model), Genshi (View), Repoze and Tosca Widgets. Create a database-driven, ready-to-extend application in minutes. All with designer-friendly templates, easy AJAX on the browser side and on the server side, with an incredibly powerful and flexible Object Relational Mapper (ORM), and with code that is as natural as writing a function. After reviewing the Documentation, check out the Tutorials web2py All in one package with no further dependencies. Development, deployment, debugging, testing, database administration and maintenance of applications can be done via the provided web interface, but not required. web2py has no configuration files, requires no installation, can be run off a USB drive: it uses Python for the Model, View and the Controller. It main features include: a built-in ticketing system to manage errors; internationalization engine and pluralization, caching system; flexible authentication system (LDAP, MySQL, janrain & more); Available for Linux, BSD, Windows, and Mac OSX; works with MySQL, PostgreSQL, SQLite , Firebird, Oracle, MSSQL and the Google App Engine via an ORM abstraction layer.
Hello World in Phyton
Before installing Django, let’s see how we can generate a sample "Hello World" web page using Python. From a Linux shell, open your favorite text editor (mine is nano, but you can also use vi or anything else) and type the following: #!/usr/bin/env python import textwrap from six.moves.BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class HelloRequestHandler(BaseHTTPRequestHandler): def do_GET(self): if self.path != '/': self.send_error(404, "Object not found") return self.send_response(200) self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() response_text = textwrap.dedent('''\ Hello World
Hello, World!
... Here we are! ''') self.wfile.write(response_text.encode('utf-8')) server_address = ('', 8000) httpd = HTTPServer(server_address, HelloRequestHandler) httpd.serve_forever() ... And that's pretty much it! This simple program can be executed and then tested by visiting http://localhost:8000/ with any browser.
Hello World with Django
Writing a Hello World sample web page with Django is definitely more difficult than doing it using blue Phyton... But there's a tremendous advantage in doing that: the scaling factor. If you're dealing with a more complex web application, you won't be able to write it using pure Phyton without losing control over the code pretty soon. The good thing about Django is that, once you learn the basics, you'll be able to deal with your projects in a comfortable fashion and with a great learning curve. Installing Django The first thing to do is to make sure that you have Django installed. Assuming you are using virtualenv, the following command should suffice: > pip install django Right after that, we need to create a Django project and a Django app: > django-admin startproject hello_world_project > cd hello_world_project > python manage.py startapp hello We now have a project called hello_world_project and an app named hello. When we executed python manage.py startapp hello, Django created a folder called hello with several files inside it. In this sample tutorial we won't use most of these files, hence we can delete them: the file that can be deleted are the following: hello/admin.py hello/models.py the whole hello/migrations folder. Writing the code Once done, edit the hello/views.py file in the following way: import textwrap from django.http import HttpResponse from django.views.generic.base import View class HomePageView(View): def dispatch(request, *args, **kwargs): response_text = textwrap.dedent('''\ Hello World
Hello, World!
... Here we are! ''') return HttpResponse(response_text) As we can see, we have basically created a Phyton class, which in Django is called a view. More specifically, this will be the class that will output the same HTML snippet we previously wrote using pure Phyton. Right after that, create a new hello/urls.py file with the following contents: from django.conf.urls import patterns, url from hello.views import HomePageView urlpatterns = patterns( '', url(r'^$', HomePageView.as_view(), name='home'), ) Next, edit the hello_world_project/urls.py file to make it looks like this: from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'', include('hello.urls')), ) As we can see by looking at the code, these urls.py files are the routing system that will be used by Django to understand what view to load whenever a specific URL is requested by a user. In a nutshell, we just told to our main project routing file (hello_world_project/urls.py) to route all the requests pointing to the site root to the app routing file (hello/urls.py), which in turn will point to the HomePageView view, that will then be executed - eventually returning the HTML content. The last thing we need to do is to edit the hello_world_project/settings.py file and remove some unused stuff that could prevent our sample web application from running. Around line 30, find a variable called INSTALLED_APPS: remove the first four items of the sequence and add 'hello' to the end. INSTALLED_APPS = ( 'django.contrib.messages', 'django.contrib.staticfiles', 'hello', ) Immediately after these lines, find the MIDDLEWARE_CLASSES variable and remove the line containing SessionAuthenticationMiddleware.  MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) That's it: our Django web application is ready. You can start it by typing the following: > python manage.py runserver And then visit http://localhost:8000/ in your browser to see it in action.
Conclusion
That's pretty much about it. If you are interested in Phyton and you would like to go further, we strongly suggest to visit one of the following resources: PhytonTips.com FullStackPhyton The Hitchhiker's Guide to Python ... and so on. See you next time, and... happy coding!   Read the full article
0 notes
bgrif001-blog · 6 years ago
Photo
Tumblr media
CREATING ANOTHER SIMPLE SERVER WITH PYTHON
Im trying to create a server that could link with the py file which could tell you whether a light has gone off or not. So at the moment i’m experimenting with different ways of coding a server. 
I used the inbuilt python library and imported the HTTPserver and BaseRequestHandler. I then create a class and pass in the baseHandler to allow me to receive a Get request which will then load up my index.html file. 
All code for this can be found on this link: https://gitlab.doc.gold.ac.uk/bgrif001/final-project-P/tree/master/The%20Py%20files%20/webserv
Once again all my code is commented so you can see exactly how it works
0 notes