树莓派 ftp服务器上怎么管理自己安装的服务器

搭建基于Flask框架的树莓派服务器 - 为程序员服务
搭建基于Flask框架的树莓派服务器
本文展示了怎么样来利用Flask框架来搭建树莓派的服务器,然后通过web方式来控制物理硬件的开关~。背后的实现原理是,在树莓派的平台上利用python语言开发包,开发IO通信程序,然后通过Flask框架,以web的方式展现出来,那么,这样就可以通过pc的web浏览器或者手持设备的web浏览器来控制实际的硬件开发,实现了物联网的远程控制。
The following is an adapted excerpt from . I especially like this section of the book because it shows off one of the strengths of the Pi: its ability to combine modern web frameworks with hardware and electronics.
Not only can you use the Raspberry Pi to get data from servers via the internet, but your Pi can also act as a server itself. There are many different web servers that you can install on the Raspberry Pi. Traditional web servers, like Apache or lighttpd, serve the files from your board to clients. Most of the time, servers like these are sending HTML files and images to make web pages, but they can also serve sound, video, executable programs, and much more.
However, there's a new breed of tools that extend programming languages like Python, Ruby, and JavaScript to create web servers that dynamically generate the HTML when they receive HTTP requests from a web browser. This is a great way to trigger physical events, store data, or check the value of a sensor remotely via a web browser. You can even create your own JSON API for an electronics project!
Flask Basics
We're going to use a Python web framework called
to turn the Raspberry Pi into a dynamic web server. While there's a lot you can do with Flask "out of the box," it also supports many different extensions for doing things such as user authentication, generating forms, and using databases. You also have access to the wide variety of standard Python libraries that are available to you.
In order to install Flask, you'll need to have pip installed. If you haven't already installed pip, it's easy to do:
pi@raspberrypi ~ $ sudo apt-get install python-pip
After pip is installed, you can use it to install Flask and its dependencies:
pi@raspberrypi ~ $ sudo pip install flask
To test the installation, create a new file called hello-flask.py with the code from below.
hello-flask.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)
Here's a breakdown of each line of code:
from flask import Flask
Load the Flask module into your Python script
app = Flask(__name__)
Create a Flask object called app
@app.route("/")
def hello():
Run the code below this function when someone accesses the root URL of the server
return "Hello World!"
Send the text "Hello World!" to the client's web browser
if __name__ == "__main__":
If this script was run directly from the command line
app.run(host='0.0.0.0', port=80, debug=True)
Have the server listen on port 80 and report any errors.
NOTE: Before you run the script, you need to know your Raspberry Pi's IP address. You can run ifconfig to find it. An alternative is to install avahi-daemon (run sudo apt-get install avahi-daemon from the command line). This lets you access the Pi on your local network through the address http://raspberrypi.local. If you're accessing the Raspberry Pi web server from a Windows machine, you may need to put
on it for this to work.
Now you're ready to run the server, which you'll have to do as root:
pi@raspberrypi ~ $ sudo python hello-flask.py
* Running on http://0.0.0.0:80/
* Restarting with reloader
From another computer on the same network as the Raspberry Pi, type your Raspberry Pi's IP address into a web browser. If your browser displays "Hello World!", you know you've got it configured correctly. You may also notice that a few lines appear in the terminal of the Raspberry Pi:
.0.1.100 - - [19/Nov/:31] "GET / HTTP/1.1" 200 -
.0.1.100 - - [19/Nov/:31] "GET /favicon.ico HTTP/1.1" 404 -
The first line shows that the web browser requested the root URL and our server returned HTTP status code 200 for "OK." The second line is a request that many web browsers send automatically to get a small icon called a favicon to display next to the URL in the browser's address bar. Our server doesn't have a favicon.ico file, so it returned HTTP status code 404 to indicate that the URL was not found.
If you want to send the browser a site formatted in proper HTML, it doesn't make a lot of sense to put all the HTML into your Python script. Flask uses a template engine called
so that you can use separate HTML files with placeholders for spots where you want dynamic data to be inserted.
If you've still got hello-flask.py running, press Control-C to kill it.
To make a template, create a new file called hello-template.py with the code from below. In the same directory with hello-template.py, create a subdirectory called templates. In thetemplates subdirectory, create a file called main.html and insert the code from below. Anything in double curly braces within the HTML template is interpreted as a variable that would be passed to it from the Python script via the render_template function.
hello-template.py
from flask import Flask, render_template
import datetime
app = Flask(__name__)
@app.route("/")
def hello():
now = datetime.datetime.now()
timeString = now.strftime("%Y-%m-%d %H:%M")
templateData = {
'title' : 'HELLO!',
'time': timeString
return render_template('main.html', **templateData)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)
Let's take a look at some of the important lines of code.
now = datetime.datetime.now()
Get the current time and store it in the object now
timeString = now.strftime("%Y-%m-%d %H:%M")
Create a formatted string using the date and time from the now object
templateData = {
'title' : 'HELLO!',
'time': timeString
Create a dictionary of variables (a set of keys, such as title that are associated with values, such as HELLO!) to pass into the template
return render_template('main.html', **templateData)
Return the main.html template to the web browser using the variables in the templateDatadictionary
&!DOCTYPE html&
&title&{{ title }}&/title&
&h1&Hello, World!&/h1&
&h2&The date and time on the server is: {{ time }}&/h2&
In main.html, any time you see a word within double curly braces, it'll be replaced with the matching key's value from the templateData dictionary in hello-template.py.
Now, when you run hello-template.py (as before, you need to use sudo to run it) and pull up your Raspberry Pi's address in your web browser, you should see a formatted HTML page with the title "HELLO!" and the Raspberry Pi's current date and time.
NOTE: While it's dependent on how your network is set up, it's unlikely that this page is accessible from outside your local network via the Internet. If you'd like to make the page available from outside your local network, you'll need to configure your router for port forwarding. Refer to your router's documentation for more information about how to do this.
Connecting the Web to the Real World
You can use Flask with other Python libraries to bring additional functionality to your site. For example, with the
Python module you can create a website that interfaces with the physical world. To try it out, hook up a three buttons or switches to pins 23, 24, and 25 as shown in this graphic:
The following code expands the functionality of hello-template.py, so copy it to a new file called hello-gpio.py. Add the RPi.GPIO module and a new route for reading the buttons, as I've done in the code below. The new route will take a variable from the requested URL and use that to determine which pin to read.
hello-gpio.py
from flask import Flask, render_template
import datetime
import RPi.GPIO as GPIO
app = Flask(__name__)
GPIO.setmode(GPIO.BCM)
@app.route("/")
def hello():
now = datetime.datetime.now()
timeString = now.strftime("%Y-%m-%d %H:%M")
templateData = {
'title' : 'HELLO!',
'time': timeString
return render_template('main.html', **templateData)
@app.route("/readPin/&pin&")
def readPin(pin):
GPIO.setup(int(pin), GPIO.IN)
if GPIO.input(int(pin)) == True:
response = "Pin number " + pin + " is high!"
response = "Pin number " + pin + " is low!"
response = "There was an error reading pin " + pin + "."
templateData = {
'title' : 'Status of Pin' + pin,
'response' : response
return render_template('pin.html', **templateData)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)
Here are the highlights:
@app.route("/readPin/&pin&")
Add a dynamic route with pin number as a variable.
GPIO.setup(int(pin), GPIO.IN)
if GPIO.input(int(pin)) == True:
response = "Pin number " + pin + " is high!"
response = "Pin number " + pin + " is low!"
response = "There was an error reading pin " + pin + "."
If the code indented below try raises an exception (that is, there's an error), run the code in the except block.
GPIO.setup(int(pin), GPIO.IN)
Take the pin number from the URL, convert it into an integer and set it as an input
if GPIO.input(int(pin)) == True:
response = "Pin number " + pin + " is high!"
If the pin is high, set the response text to say that it's high
response = "Pin number " + pin + " is low!"
Otherwise, set the response text to say that it's low
response = "There was an error reading pin " + pin + "."
If there was an error reading the pin, set the response to indicate that
You'll also need to create a new template called pin.html. It's not very different from main.html, so you may want to copy main.html to pin.html and make the appropriate changes as shown
&!DOCTYPE html&
&title&{{ title }}&/title&
&h1&Pin Status&/h1&
&h2&{{ response }}&/h2&
With hello-gpio.py running, when you point your web browser to your Raspberry Pi's IP address, you should see the standard "Hello World!" page we created before. But add/readPin/24 to the end of the URL, so that it looks something likehttp://10.0.1.103/readPin/24. A page should display showing that the pin is being read as low. Now hold down the button connected to pin 24
it should now show up as high!
Try the other buttons as well by changing the URL. The great part about this code is that we only had to write the function to read the pin once and create the HTML page once, but it's almost as though there are separate webpages for each of the pins!
Project: WebLamp
In chapter 7 of , Shawn and I show you how to use Raspberry Pi as a simple AC outlet timer using the Linux job scheduler, cron. Now that you know how to use Python and Flask, you can now control the state of a lamp over the web. This basic project is simply a starting point for creating Internet-connected devices with the Raspberry Pi.
And just like how the previous Flask example showed how you can have the same code work on multiple pins, you'll set up this project so that if you want to control more devices in the future, it's easy to add.
Connect a Power Switch Tail II to pin 25 of the Raspberry Pi, as shown in the illustration below. If you don't have a Power Switch Tail, you can connect an LED to the pin to try this out for now.
If you have another PowerSwitch Tail II relay, connect it to pin 24 to control a second AC device. Otherwise, just connect an LED to pin 24. We're simply using it to demonstrate how multiple devices can be controlled with the same code.
Create a new directory in your home directory called WebLamp.
In WebLamp, create a file called weblamp.py and put in the code from below:
weblamp.py
import RPi.GPIO as GPIO
from flask import Flask, render_template, request
app = Flask(__name__)
GPIO.setmode(GPIO.BCM)
# Create a dictionary called pins to store the pin number, name, and pin state:
: {'name' : 'coffee maker', 'state' : GPIO.LOW},
: {'name' : 'lamp', 'state' : GPIO.LOW}
# Set each pin as an output and make it low:
for pin in pins:
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, GPIO.LOW)
@app.route("/")
def main():
# For each pin, read the pin state and store it in the pins dictionary:
for pin in pins:
pins[pin]['state'] = GPIO.input(pin)
# Put the pin dictionary into the template data dictionary:
templateData = {
'pins' : pins
# Pass the template data into the template main.html and return it to the user
return render_template('main.html', **templateData)
# The function below is executed when someone requests a URL with the pin number and action in it:
@app.route("/&changePin&/&action&")
def action(changePin, action):
# Convert the pin from the URL into an integer:
changePin = int(changePin)
# Get the device name for the pin being changed:
deviceName = pins[changePin]['name']
# If the action part of the URL is "on," execute the code indented below:
if action == "on":
# Set the pin high:
GPIO.output(changePin, GPIO.HIGH)
# Save the status message to be passed into the template:
message = "Turned " + deviceName + " on."
if action == "off":
GPIO.output(changePin, GPIO.LOW)
message = "Turned " + deviceName + " off."
if action == "toggle":
# Read the pin and set it to whatever it isn't (that is, toggle it):
GPIO.output(changePin, not GPIO.input(changePin))
message = "Toggled " + deviceName + "."
# For each pin, read the pin state and store it in the pins dictionary:
for pin in pins:
pins[pin]['state'] = GPIO.input(pin)
# Along with the pin dictionary, put the message into the template data dictionary:
templateData = {
'message' : message,
'pins' : pins
return render_template('main.html', **templateData)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)
Since there's a lot going on in this code, I've placed on the explanations inline, as comments.
Create a new directory within WebLamp called templates.
Inside templates, create the file main.html:
&!DOCTYPE html&
&title&Current Status&/title&
&h1&Device Listing and Status&/h1&
{% for pin in pins %}
&p&The {{ pins[pin].name }}
{% if pins[pin].state == true %}
is currently on (&a href="/{{pin}}/off"&turn off&/a&)
{% else %}
is currently off (&a href="/{{pin}}/on"&turn on&/a&)
{% endif %}
{% endfor %}
{% if message %}
&h2&{{ message }}&/h2&
{% endif %}
There are two templating concepts being illustrated in this file. First:
{% for pin in pins %}
&p&The {{ pins[pin].name }}
{% if pins[pin].state == true %}
is currently on (&a href="/{{pin}}/off"&turn off&/a&)
{% else %}
is currently off (&a href="/{{pin}}/on"&turn on&/a&)
{% endif %}
{% endfor %}
This sets up a for loop to cycle through each pin, print its name and its state. It then gives the option to change its state, based on its current state. Second:
{% if message %}
&h2&{{ message }}&/h2&
{% endif %}
This if statement will print a message passed from your Python script if there's a message set (that is, a change happened).
In terminal, navigate to the WebLamp directory and start the server (be sure to use Control-C to kill any other Flask server you have running first):
pi@raspberrypi ~/WebLamp $ sudo python weblamp.py
The best part about writing the code in this way is that you can very easily add as many devices that the hardware will support. Simply add the information about the device to the pins dictionary. When you restart the server, the new device will appear in the status list and its control URLs will work automatically.
There's another great feature built in: if you want to be able to flip the switch on a device with a single tap on your phone, you can create a bookmark to the addresshttp://ipaddress/pin/toggle. That URL will check the pin's current state and switch it.
For more information about using Raspberry Pi, check out .
文章节选:
,首发于。
天空一朵雨做的云
原文地址:, 感谢原作者分享。
您可能感兴趣的代码1. 调整pi的GPU内存占用大小
作为web服务器,不需要输出视频信号,所以尽量缩小GPU的内存用量,以便最大化pi的性能。
1 sudo raspi-config
选择Advanced Options -& Memory Split ,然后填入16 ,保存后需要重启
2. 更新你的pi
1 sudo apt-get update
2 sudo apt-get upgrade
  更新完成后最好重启一下
3. 安装服务器软件
我们来安装最常用的LAMP,即 Linux, Apache, MySql 和 PHP
3.1 安装 Apache 和 PHP
1 sudo apt-get install apache2 php5 libapache2-mod-php5
3.2 安装 MySql(安装过程中需要设置数据库密码)
1 sudo apt-get install mysql-server mysql-client php5-mysql
3.3 安装完成后需要重启一下 apache
1 sudo service apache2 restart
所需软件都安装完成后,服务器基本就算是架设好了,这时候打开你的浏览器,输入127.0.0.1,应该就可以看到一个这样的页面:
网站根目录默认在 /var/www/html 中,如果你想获得更多关于服务器的信息,可以在网站根目录中放一个php探针页面,推荐&&,然后访问该页面 127.0.0.1/tz.php 就可以读取出关于服务器的所有详细信息了
参考资料:
阅读(...) 评论()22款树莓派媒体服务器,你想DIY哪个-树莓派吧
22款树莓派媒体服务器,你想DIY哪个
作者: 来源:
树莓派电脑一直以来都广受欢迎,它最常见的用途就是众所周知的媒体服务器。想不想自己动手做一个呢?快跟着小编一起来看看这份清单吧!这份清单包括软件教...
树莓派电脑一直以来都广受欢迎,它最常见的用途就是众所周知的媒体服务器。想不想自己动手做一个呢?快跟着小编一起来看看这份清单吧!这份清单包括软件教程,以及安装不同样式的音响的方法。如何安装软件呢?在这个看脸的时代,你会不会担心你的媒体中心长得不好看影响它的功能?答案是“不”!不管你的媒体中心看起来美不美观,这都不会影响软件运行。现在,点击下面的链接开始安装软件吧!1.想安装XBOX媒体中心(XBMC)的话,Lifehacker公司的这个视频可以帮你在30分钟内搞定。MAKE公司打赌,尽管他们是用图片讲解,他们的教程也可以让你可以在20分钟之内搞定,可以来试试哦。2.如何通过硬盘驱动把树莓派设置成流媒体关闭状态?这有一个教程链接。3.使用MiniDLNA设置的教程。4.想知道如何建立最棒的树莓派媒体服务器,流媒体系统如何运行?点击这里。5.不想错过一大波风暴式图片资源学习通过bt客户端安装XBMC就点击这里吧!6.这篇文章介绍了RPi成为最赞的Linux Distos的理由,并附有简介配图。7.另一款神器Pi MusicBox,安装以后RPi即可支持播放Spotify,Google Music等其他云端音乐。复古样式想要运行程序,软件是必不可少的,但是你如果没有一款过硬的软件也是不行的。不过不用担心,你只需要一台电脑,看我如何教你以旧换新。1.看上面这张照片,一个四十年代的收音机都可以重新拿出来做RPi了还有什么是不可能的呢?2.这是另一款只读声音的收音机,还有一款具有简洁动态转换,“频繁”的拨号选择钮。3.还有一种更令人咋舌的,一款只能播放BBC 4台的收音机现在也能用来做RPi了。作为一个美国人,尽管我不太相信这个,但是不妨试一下。4.还有这款1932年的收音机,Mephisto II在当时看来还是很高端的,现在也可以用来以旧换新了。5.下面这个视频展示了在一款1930年代的收音机和原代
iPod之间如何通过Spotify磁带盘实现以旧换新的。磁带一放进去,就会有一个播放列表,每一面都有一个,收音机上的按键也都还能正常使用。6.下面这个视频中的Audio Infuser 4700也很有意思,通过RPI可以实现连接WIFI,转台,在CRT显示器上呈现5秒钟的波形。7.尽管现在市面上还在生产Mason jars,我也还是觉得它已经过时了,这是用它来完成的一款RPi,或许也可以给你带来意外惊喜!当下流行的样式复古样式有时候挺独特的,但是有的人会更青睐21世纪里新兴的媒体流工具。下面介绍几款设计上走在前端的RPi。1.如果你想买一个方便的话,这有一款自带风扇的(上图所示),还有一款可以挂载到电视机背部的。2.下面这款,绝对是超轻薄,有了它你甚至可以把它放到恒温器中。3.如果你手头没那么多工具,试试这款用乐高拼成的RPi吧,或者试试用Altoids锡盒。4.这款SqueezeBerry音乐播放器的颜色似乎又重新流行起来,值得一提的是,它的外壳完全是车库里的旧木头做成的,是不是很炫酷!via
1.树莓派吧遵循行业规范,任何转载的稿件都会明确标注作者和来源,如有版权问题,请联系QQ删除。;
2.树莓派吧的原创文章,请转载时务必注明文章作者和"来源:树莓派吧",不尊重原创的行为树莓派吧或将追究责任;
3.作者投稿可能会经树莓派吧编辑修改或补充。
关注微信公众号,了解最新精彩内容
通过E-mail将您的想法和建议发给我们
稿件投诉:
版权建议:
官方客服QQ:
官方QQ群:
微信公众号:shumeipaiba}

我要回帖

更多关于 win7安装服务器管理器 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信