python做一个随机图片输出网站,包括前端和后端,要有代码
时间: 2024-01-20 07:04:34 浏览: 147
好的,关于您的问题,以下是一个可以实现随机图片输出的Python前后端代码组合示例:
前端代码(index.html):
```html
<!DOCTYPE html>
<html>
<head>
<title>随机图片网站</title>
</head>
<body>
<h1>随机图片网站</h1>
<img id="randomImg" src="">
<button onclick="getRandomImg()">随机图片</button>
<script>
function getRandomImg() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("randomImg").src = this.responseText;
}
};
xhr.open("GET", "/get-random-img", true);
xhr.send();
}
</script>
</body>
</html>
```
后端代码(app.py):
```python
from flask import Flask, send_file
import random
app = Flask(__name__)
@app.route("/")
def index():
return send_file("index.html")
@app.route("/get-random-img")
def getRandomImg():
imgUrls = [
"https://picsum.photos/200/300",
"https://picsum.photos/seed/picsum/200/300",
"https://picsum.photos/200/300/?blur"
]
randomImgUrl = random.choice(imgUrls)
return randomImgUrl
if __name__ == "__main__":
app.run()
```
以上代码使用了Flask框架,并使用了picsum.photos提供的随机图片URL作为随机图片的来源。您可以替换为自己的图片URL,或者自己实现图片生成逻辑。要运行此代码,您需要安装Flask和requests库:
```bash
pip install flask requests
```
运行命令:
```bash
python app.py
```
您可以在浏览器中访问http://127.0.0.1:5000/来查看随机图片输出的效果。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044736.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)